如何摆脱这个循环

时间:2014-06-02 15:01:30

标签: python loops while-loop

伙计们,我试图突破这个循环..

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!")

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

3 个答案:

答案 0 :(得分:2)

您的代码存在两个问题:

  1. 根本没有循环。你应该使用while True
  2. 之类的东西
  3. 您应该使用break来摆脱循环
  4. 代码:

    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
    

答案 1 :(得分:1)

在每个'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

答案 2 :(得分:0)

这是否在

之内
while True:
    ...

阻止?

您可以使用break跳出循环。