2

Im doing an activity to extend my existing code to check for user input and I can't get it to work properly.

  • First attempt:
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")
  • Second Try
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

2
  • Welcome to Stack Overflow! Commented Apr 12, 2019 at 12:31
  • You'd better validate the input before appending it to StudentGender. Commented Apr 12, 2019 at 12:36

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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")

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.