首页 > 解决方案 > 如何使这个循环重复直到添加了正确的值,Python

问题描述

我试图让下面的代码重复,直到输入正确的字符串值之一。

while True:
    if value in ['man united', 'man city', 'liverpool', 'chelsea']:
        print(tabulate(data[value]))
        break
    if value not in ['man united', 'man city', 'liverpool', 'chelsea']:
        print("You entered a wrong option, Please enter a correct option")
        print(f"1: {options}")

我尝试了几种不同的方法,但无法完全实现我想要的。此代码在 python 函数中。

任何帮助是极大的赞赏。Python 新手

标签: pythonloops

解决方案


这就是我认为你可以做到的方式, l 只是一个包含选项的列表,但你不必使用它。

l = ['man united', 'man city', 'liverpool', 'chelsea']
value = input()

while value not in l:
    print("You entered a wrong option, Please enter a correct option")
    print(f"1: {options}")
    value = input() #or however you want to change the value variable

print(tabulate(data[value])) #this will execute only once the correct choice has been selcted

推荐阅读