Reputation: 35
I am a GCSE student needing help for my computer science case study. I would like to check if an input is in a list as validation for my code. Here is a small example of what im trying to do.
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
Try running it, it has some sort of looping error and I assume the while is probably in the wrong places. I want the program to check if the input is in the list and if it is, break from the whole loop, and if it isn't, then it will ask the user to input again. If someone can rewrite/edit the code then it will be appreciated. And please take into consideration that this should be GCSE level.
Upvotes: 0
Views: 398
Reputation: 8273
Just to point out there is a library Calendar.day_name to get all the day names which can be used
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')
Upvotes: 0
Reputation: 10590
You should use the approach @JosueCortina mentions.
But to point out what's going on in your code, the break
will only break from the for loop. So you are stuck in an infinite while loop. The while loop should be removed here. Also, your else
should go with the for
loop, not the if
statement.
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
Upvotes: 2
Reputation: 2624
Use the in operator:
Days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
DayChoice = input("Enter a day")
if DayChoice not in Days:
print('Enter correct input')
Upvotes: 4