samedi 16 mai 2015

looping if/elif statements in python until the user inputs one of the correct answers [duplicate]

This question already has an answer here:

How do you create a code that repeats an if/elif statement until one of the required inputs is given?

I tried using a function but need to carry some variables outside the function. I was wondering about using a "while" loop but don't know how to use this in a way that it carries on whilst the required input isn't entered. The if/elif statement I have so far is:

#ask users class:
Class=input("Select your class: 1,2 or 3")
#open and write to file 1,2 or 3:
if (Class == "1" or Class.lower()=="one"):
    f=open("class1.txt", "a+")

elif (Class == "2" or Class.lower()=="two"):
    f=open("class2.txt", "a+")

elif (Class == "3" or Class.lower()=="three"):
    f=open("class3.txt", "a+")
#write the persons name and score to the file
f.write(Name +'\t')
f.close()

At the moment if anything apart from what is in the if/elif statements is entered the shell restarts

Aucun commentaire:

Enregistrer un commentaire