Reputation: 63
Im doing an activity to extend my existing code to check for user input and I can't get it to work properly.
while 5 > appcounter:
StudentGender.append (input(StudentName[namecount]+",Please Enter Student Gender M or F:"))
if StudentGender[appcounter] == "M":
appcounter = appcounter + 1
namecount = namecount + 1
elif StudentGender[appcounter] == "F":
appcounter = appcounter + 1
namecount = namecount + 1
else:
print("Not a valid input")
for Counter in range (ConstNoStudents+1):
try:
StudentGender[Counter] = (input(StudentName[namecount]+",are you Male or Female, Please use M or F:") )
StudentGender[Counter] = "M" or "F" or "f" or "m"
namecount = listcount+1
except:
print("That is not a valid number")
I ideally want it to identify when the user type's something other than M or F in and Get the user to re-enter the value without adding anything extra to the list
Upvotes: 2
Views: 81
Reputation: 2027
You would need to get the input in a loop and check if one of the correct values was entered and if it was not, then repeat the loop.
You can also apply .upper()
to the gender selection, instead of specifying the lower case versions of the gender values.
invalid_gender = True
while invalid_gender:
gender = input('Please Enter Student Gender (M or F):')
if gender.upper() not in ['M', 'F']:
print('Invalid gender! Please, try again.')
else:
invalid_gender = False
Upvotes: 1
Reputation: 2477
Rearranging your code, you need to prompt the user again if his input is invalid. You can do so with a while loop :
for index in range(ConstNoStudents+1):
input = input(StudentName[index]+", are you Male or Female, Please use M or F:")
while not input.upper() in ["M", "F"]:
input = input("Invalid input. Please use M or F :")
StudentGender[index] = input
Upvotes: 1
Reputation: 1148
Use this pattern:
accepted_inputs = ["M", "F"]
while True:
user_input = input("message")
if user_input in accepted_inputs:
break
print("Bad input, try again")
Upvotes: 1