python - 初学者 python 循环

标签 python python-3.x

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

我读过一些类似的问题,但找不到有效的解决方案。

我只是想在脚本中提出相同的问题,直到提到列出的猫的名字。因此,如果输入一个不在宠物列表中的名称,如“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

关于python - 初学者 python 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44674222/

相关文章:

Python - 确认文本文件中的字符串与格式匹配

python - 从列表转换元组

python - 沿 N 维 numpy 数组的每个维度对每个第 n 个元素进行索引

python - 如何加快 Python 的执行速度?

python - 如何制作线性函数的反函数

python-3.x - 在 python 中创建子图 plotly

python - 引发错误类与类实例的优缺点是什么

python - CUDA错误: CUBLAS_STATUS_INVALID_VALUE error when training BERT model using HuggingFace

python - 嵌入层后的 LSTM - 值错误 : Isn't symbolic tensor?

python - 如何初始化一个列表并在一行中用另一个列表扩展它?