简体   繁体   中英

Problem with while loop in Python, repeating string

a = input('Enter your username...')
while (a == 'SuperGiraffe007&'):
  print('Welcome!')
else:
  print("Try again...")
a = input('Enter your username...')
while (a == 'SuperGiraffe007&'):
  print('Welcome!')
  • The code functions correctly but when I input the correct username the string 'Welcome!' repeats forever which crashes my browser. How do I stop it from repeating and only print once?

It looks like you have misunderstood what a while loop does. It checks the condition you give it and keeps on repeating the body of the loop for as long as the condition is true. The infinite loop you describe is exactly what you're asking for with your code.

What I think you want is a loop that stops when the user enters the correct username:

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!')

I think you need to use if instead of while . Also, you don't need the parenthesis when using a conditional in python. Use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM