0

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.

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Azat Ibrakov Jan 28 '19 at 19:05
  • Possible duplicate of [Check if item is in an array / list](https://stackoverflow.com/questions/11251709/check-if-item-is-in-an-array-list) – Pedro Martins de Souza Jan 28 '19 at 19:11
  • Possible duplicate of [Check if item is in an array / list](https://stackoverflow.com/questions/11251709/check-if-item-is-in-an-array-list) – Pedro Martins de Souza Jan 28 '19 at 19:12

3 Answers3

4

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')
JoshuaCS
  • 2,524
  • 1
  • 13
  • 16
2

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
busybear
  • 10,194
  • 1
  • 25
  • 42
0

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')
mad_
  • 8,121
  • 2
  • 25
  • 40