首页 > 解决方案 > Python中的while循环问题,重复字符串

问题描述

a = input('Enter your username...')
while (a == 'SuperGiraffe007&'):
  print('Welcome!')
else:
  print("Try again...")
a = input('Enter your username...')
while (a == 'SuperGiraffe007&'):
  print('Welcome!')

标签: pythonwhile-loophelper

解决方案


看起来您误解了while循环的作用。它检查你给它的条件,只要条件为真,它就会不断重复循环体。您描述的无限循环正是您对代码的要求。

我认为您想要的是当用户输入正确的用户名时停止的循环:

a = input('Enter your username...')
while a != 'SuperGiraffe007&': # stop looping when the name matches
    print("Try again...")
    a = input('Enter your username...') # ask for a new input on each loop
print('Welcome!')

推荐阅读