检查输入是否为列表的一部分

时间:2019-01-28 18:58:19

标签: python

我是一名GCSE学生,需要有关我的计算机科学案例研究的帮助。 我想检查输入是否在列表中,以验证我的代码。这是我正在尝试做的一个小例子。

Days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] #The array

DayChoice = input("Enter a day") #Asking user to input day
while True:
    for i in Days:               #Trying to loop through days to see if input matches list
        if DayChoice == i:
            print("correct input")  

            break                           #If yes then end validation

        else:
            print("enter correct input") #If wrong ask to input again

尝试运行它,它有某种循环错误,我认为那一阵子可能在错误的地方。我希望程序检查输入是否在列表中,如果是,则从整个循环中断开,如果不是,则它将要求用户再次输入。如果有人可以重写/编辑代码,则将不胜感激。并且请考虑到这应该是GCSE级别。

3 个答案:

答案 0 :(得分:4)

使用 in 运算符:

Days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

DayChoice = input("Enter a day")

if DayChoice not in Days:
    print('Enter correct input')

答案 1 :(得分:2)

您应该使用@JosueCortina提到的方法。

但是要指出代码中发生的事情,break只会从for循环中中断。因此,您陷入了无限的while循环中。 while循环应在此处删除。另外,您的else应该带有for循环,而不是if语句。

Days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] #The array

DayChoice = input("Enter a day") #Asking user to input day
for i in Days:               #Trying to loop through days to see if input matches list
    if DayChoice == i:
        print("correct input")  
        break                        #If yes then end validation
else:
    print("enter correct input") #If wrong ask to input again

答案 2 :(得分:0)

只需指出有一个库Calendar.day_name来获取所有可以使用的日期名称

import calendar
possible_days = [day[:3] for day in (calendar.day_name)]
day_input = input("Enter a day")

if day_input not in possible_days :
    print('Enter correct input')
相关问题