繁体   English   中英

初学者python循环

[英]Beginner python loop

python 的新手并且在尝试让循环工作时可能是一个基本问题。

我已经阅读了一些以前的类似问题,但找不到有效的解决方案。

我只是想在脚本中提出同样的问题,直到提到列出的猫名。 因此,如果输入“Scott”等不在宠物列表中的名称,它将要求再次尝试输入宠物名称。

myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name.')
name = input()
if name not in myPets:
    print('I do not have a pet named ' + name + ' try again')

else:
    print(name + ' is my pet.')

您可以使用while循环来重复,直到用户输入正确的输入。 使用break退出循环。

myPets = ['Zophie', 'Pooka', 'Fat-tail']
while True:
    print('Enter a pet name.')
    name = input()
    if name not in myPets:
        print('I do not have a pet named ' + name + ' try again')
    else:
        print(name + ' is my pet.')
        break

对于此任务,您应该使用像这样的 while 循环:

myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name.')
name = input()
while name not in myPets:
    print('Enter a valid pet name.')
    name = input()
print(name + ' is my pet.')

每次用户输入内容时,都会评估条件。 如果您的条件正确,您将继续要求用户提供其他输入,直到它符合您的要求。

while是您需要的关键字。 使用while循环
它可以帮助您在满足条件时重复一组语句(即直到发生新的事情,例如输入的名字是您的宠物之一)。

您还可以将输入消息作为参数传递给 input() 方法。

myPets = ['Zophie', 'Pooka', 'Fat-tail']
name = input("Enter pet name")
while name not in myPets:
    print('I do not have a pet named ' + name + ' try again')
    name = input("Enter pet name")
print(name + ' is my pet.')

这是您要找的:

myPets = ['Zophie', 'Pooka', 'Fat-tail']

done=Fasle
while not done:
    name=input("enter a pet name: ")
    if name in myPets:
       done=True
       print(name + ' is my pet.')
    else:
        print('I do not have a pet named ' + name + ' try again')

您可以使用一个简单的 while 循环:

myPets = ['Zophie', 'Pooka', 'Fat-tail']
loop=0
while loop==0:
    print('Enter a pet name.')
    name = input()
    if name not in myPets:
        print('I do not have a pet named ' + name + ' try again')

    else:
        print(name + ' is my pet.')
        loop=loop+1

或者:

使用递归循环(不推荐):

myPets = ['Zophie', 'Pooka', 'Fat-tail']
def ask():
    print('enter pet name')
    name = input()
    if name not in myPets:
        print('I do not have a pet named ' + name + ' try again')
        ask()

    else:
        print(name + ' is my pet.')

ask()

暂无
暂无

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

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