samedi 27 octobre 2018

Restarting a User-Input Function If User Inputs are Invalid

I am fairly new to Python, and programming.

I've been browsing around about how to do exactly this, restarting a user defined function if the inputs from the user are not valid, and most answers I have came across feature while loops, I cannot seem to correctly implement it into my code.

My code looks like this:

mchoices = input('Enter A or B or C or D or E or F: ')
def getRate(choices):
    if choices ==  'A':
        return 'Rate = ' + str(options[0]) + '%'
    elif choices == 'B':
        return 'Rate = ' + str(options[1]) + '%'
    elif choices == 'C':
        return 'Rate = ' + str(options[2]) + '%'
    elif choices == 'D':
        return 'Rate = ' + str(options[3]) + '%'
    elif choices == 'E':
        return 'Rate = ' + str(options[4]) + '%'
    elif choices == 'F':
        return 'Rate = ' + str(options[5]) + '%'
    else:
        return 'Please enter a valid option'
print(getRate(mchoices))

options is equal to a range (1,20) and radint(2,6), I don't think it's relevant to my problem but I am mentioning this in case you are confused about what it is. If it is relevant, I'll throw that part of the code in as well.

The main issue I am having is that towards the bottom, in the "else" part of my code, on top of having it return "Please enter a valid option" I would also like to have it restart the program so that the user can perform another input.

I expect the answer to do something with a while loop, which is fine, I just can't seem to do it myself.

Aucun commentaire:

Enregistrer un commentaire