【问题标题】:Python - break out into first while loop?Python - 进入第一个while循环?
【发布时间】:2020-01-23 21:45:37
【问题描述】:

好的,我有一个基于此处输入的 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

打印完元音数后,我需要中断并提示输入新用户名。但是 break 会导致程序退出,并且 continue 会无限重复上一次打印。

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

【问题讨论】:

  • if 语句和循环不需要括号,也不需要在output() 的结果上调用str()

标签: python while-loop


【解决方案1】:

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

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

不输入则程序结束(直接回车)

【讨论】:

  • str(input(...)) 将输入转换成字符串吗?根据the official documentationinput“从输入中读取一行,将其转换为字符串(去除尾随的换行符),然后返回”。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    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!
    

    【讨论】:

      【解决方案4】:

      我会在循环中使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-06
        • 2019-08-11
        • 2016-01-18
        • 1970-01-01
        • 2015-03-08
        • 2012-08-26
        • 2021-03-26
        相关资源
        最近更新 更多