【问题标题】:How do I get a while loop to repeat if input invalid?如果输入无效,如何让while循环重复?
【发布时间】:2020-09-01 21:06:54
【问题描述】:

我是 python 的新手,正在努力处理 while 循环以及输入如何决定执行的内容。这是我要查找的内容:如果用户输入了无效的国家/地区 ID,则希望他们被提示重试。如果他们输入了一个有效的国家 ID,就像要执行的代码一样。最后,如果他们在提示输入国家 ID 时键入“结束”,例如程序结束。这是我目前所拥有的:

while True:
    my_country = input('Enter a valid country: ')
    if my_country in unique_countries:
        print('Thanks, one moment while we fetch the data')

Some code here

  #Exit Program
    else:
        my_country == "end"
        break 

我遇到的问题是,正如目前所写的那样,如果我输入一个无效的国家,它会结束程序而不是再次提示我。先感谢您。我也是堆栈溢出的新手,对于可怕的格式感到抱歉。

【问题讨论】:

  • 您是否查看过此问题是否已在此处提出并回答?这可以帮助您更快地解决您的问题,而不是发布和等待某人回复。

标签: python python-3.x if-statement input while-loop


【解决方案1】:

将您的 while 循环设置为 False。按照下面的代码:

unique_countries = ['India', 'USA', 'Canada', 'Japan']

valid = True
while valid:
    my_country = input('Enter a valid country: ')
    if my_country in unique_countries:
        print('Thanks, one moment while we fetch the data')
        # Some code here
        valid = False # This will Exit Program
    elif my_country == "end":
        valid = False
    else:
        print("Country Name entered is not valid...")

【讨论】:

    【解决方案2】:

    解决方法是添加:

    if my_country not in unique_countries:
       continue
    

    就在您的第一个 if 语句之前。 希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      您可以从

      编辑您的代码
      else:
              my_country == "end"
              break 
      

      到 -

      elif my_country == "end":
          break 
      

      【讨论】:

        【解决方案4】:

        给你:

        while True:
            my_country = raw_input('Enter a valid country:')
            if my_country in unique_countries:
                print('Thanks, one moment while we fetch the data')
                break
            elif  my_country == "end":
                break
            else:
                continue
        

        【讨论】:

          【解决方案5】:

          你需要一个elif。试试这个:

          while True:
              my_country = input('Enter a valid country: ')
              if my_country in unique_countries:
                  print('Thanks, one moment while we fetch the data')
                  # Some code here
                  #Exit Program
              elif my_country == "end":
                  break
              else:
                  print ("Try again.") 
          

          编辑

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-10-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多