繁体   English   中英

Python - 进入第一个 while 循环?

[英]Python - break out into first while loop?

好的,我有一个基于这里输入的 while 循环 -

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

打印元音数量后,我需要突破并提示输入新用户名。 但中断导致程序退出,并继续无限重复最后一次打印。

我怎样才能回到第一个输入?

在循环中包含第一个输入:

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()

当你没有输入时程序将结束(直接按回车键)

如果您想重复获取用户名,那么该语句必须在循环中。 一种标准方法是在循环底部重复该代码。

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()

您需要在循环内获得另一个用户输入:

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!

我会使用ifbreak内循环:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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