【问题标题】:how to break out of this while loop [closed]如何打破这个while循环[关闭]
【发布时间】:2014-07-22 18:04:45
【问题描述】:

伙计们,我正试图摆脱这个 while 循环..

starterP=input("Would you rather Torchik, Mudkip, or Bulbasaur? Choose wisely.")
if starterP=='Torchik' or starterP=='torchik':
        print("You have picked Torchik!")
if starterP=='Mudkip' or starterP=='mudkip':
        print("You have picked Mudkip!")
if starterP=='Bulbasaur' or starterP=='bulbasaur':
        print("You have picked Bulbasaur!")

如果程序没有输入其中一个选项,我希望程序继续要求输入。每当他们输入与三个选项匹配的正确输入时,就会跳出循环并继续下一个代码。

【问题讨论】:

  • 没有循环...(你试过break吗?)
  • 您发布的代码不包含while 声明...

标签: python loops while-loop


【解决方案1】:

您的代码有两个问题:

  1. 您根本没有循环。你应该使用类似while True
  2. 您应该使用break 来跳出循环

代码:

while True:
    starterP=input("Would you rather Torchik, Mudkip, or Bulbasaur? Choose wisely.")
    if starterP=='Torchik' or starterP=='torchik':
            print("You have picked Torchik!")
            break
    if starterP=='Mudkip' or starterP=='mudkip':
            print("You have picked Mudkip!")
            break
    if starterP=='Bulbasaur' or starterP=='bulbasaur':
            print("You have picked Bulbasaur!")
            break
    print("Please pick an actual Pokemon") #let user know they didn't pick a valid option

【讨论】:

    【解决方案2】:

    在您的每个“if”语句下,只需像这样放置“break”:

    while True:
    
        if starterP=='Torchik' or starterP=='torchik':
            print("You have picked Torchik!")
            break 
    
        if starterP=='Mudkip' or starterP=='mudkip':
            print("You have picked Mudkip!")
            break
    
        if starterP=='Bulbasaur' or starterP=='bulbasaur':
            print("You have picked Bulbasaur!")
            break
    

    【讨论】:

      【解决方案3】:

      这是在一个内

      while True:
          ...
      

      阻止?

      你可以使用break跳出循环。

      【讨论】:

        猜你喜欢
        • 2020-05-31
        • 1970-01-01
        • 1970-01-01
        • 2018-05-18
        • 2022-12-10
        • 1970-01-01
        • 2020-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多