简体   繁体   中英

Python - break out into first while loop?

Alright, I have a while loop based on an input here -

username = str(input('whats your favorite word? (enter to quit)')).strip().lower()
while(len(username) > 0):
    counter = 0
    for c in username:
        if(c == 'a' or c == 'e' or c == 'i' or c == 'u' or c == 'o'):
            counter+=1
    ending = 'vowels' if counter > 1 else 'vowel'
    print(f"word has {counter} {ending}!")
    break

After printing number of vowels I need to break out and prompt for a new username. But break results in the program exiting, and continue infinitely repeats the last print.

How can I break out back to the first input?

Include the first input in the loop:

username = str(input('whats your favorite word? (enter to quit)')).strip().lower()
while(len(username) > 0):
    counter = 0
    for c in username:
        if(c == 'a' or c == 'e' or c == 'i' or c == 'u' or c == 'o'):
            counter+=1
    ending = 'vowels' if counter > 1 else 'vowel'
    print(f"word has {counter} {ending}!")
    username = str(input('whats your favorite word? (enter to quit)')).strip().lower()

The program will end when you give no input (press enter directly)

If you want to repeat getting usernames, then that statement has to be within a loop. One standard way is to repeat that code at the bottom of your loop.

username = str(input('whats your favorite word? (enter to quit)')).strip().lower()
while(len(username) > 0):
    counter = 0
    for c in username:
        if(c == 'a' or c == 'e' or c == 'i' or c == 'u' or c == 'o'):
            counter+=1
    ending = 'vowels' if counter > 1 else 'vowel'
    print(f"word has {counter} {ending}!")
    # Get another username
    username = str(input('whats your favorite word? (enter to quit)')).strip().lower()

You need to get another user input inside the loop :

username = str(input('whats your favorite word? (enter to quit)')).strip().lower()
while(len(username) > 0):
    counter = 0
    for c in username:
        if(c == 'a' or c == 'e' or c == 'i' or c == 'u' or c == 'o'):
            counter+=1
    ending = 'vowels' if counter > 1 else 'vowel'
    print(f"word has {counter} {ending}!")
    username = str(input('whats your favorite word? (enter to quit)')).strip().lower() # Here!

I'd use if and break inside loop:

while True:
    username = str(input('whats your favorite word? (enter to quit)')).strip().lower()
    if not username:  # check if username is an empty string
        break
    # calculations and print are here

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