Nitin Babu Nitin Babu - 2 months ago 6
Python Question

How to print info when 2 things are correct and to use the input fuction when the those two things are incorrect

I am doing a controlled assessment. I have this code :

# user Qualifications
print("\nQualification Level")

print("\n""\"AP\" = Apprentice",
"\n\"FQ\" = Fully-Qualified")
user_qual = input("Enter you Qualification Level: ")


When the
user_qual
is equal to
AP
or
FQ
I want to print "correct". But when the
user_qual
is not equal to either
AP
or
FQ
, I want to print an error message and re-ask the
user_qual
input question. However, I tried many different ways but couldn't do it.

Please just give a simple solution and nothing complicated. I am just a beginner and learning the basics.

Answer

You need to turn your code into a function so it can be called again, if the criteria are not met:

def prompt():
    # user Qualifications
    print('\nQualification Level')
    print('\n"AP" = Apprentice\n"FQ" = Fully-Qualified')

    user_qual = input('Enter you Qualification Level: ')

    if user_qual not in ('AP','FQ'):
        prompt() # Criteria not met, so ask again
    print('Correct!') # Criteria met, don't ask again


# Call the function the first time
prompt()

As @IanAuld mentions in the comments, if you want to allow users to provide the answer (ie. AP) in a case insensitive manner (so users can type 'ap' instead), you would want to convert the case before evaluating it, like so:

if user_qual.upper() not in ('AP','FQ'):
    ...rest of code...
Comments