I'm a beginner in Python. I want to create a textual game, with some MCQ in it, and to save some code, I created a function which asks and wait for an answer (input()) but it can just accept some answers (eg a, b, c, d...), but if it isn't a valid answer, it repeats the question (while loop). It works, but even if I answer correctly, it's repeating. Can you help me please?
Here is the function,
def carsaction(*instructions):
"""
Fonction servant à faire un choix pour interagir avec soi même.
"""
commande = str(None)
while commande.lower() != instructions:
commande = str(input("Quelle action choisissez-vous?"))
if commande.lower() == instructions:
break
else:
print("Réponse non valide!")
time.sleep(3)
continue
And when I use it:
carsaction("a","b")
___ This is something else
print("Vous vous trouvez quelque par. Que faites-vous?")
time.sleep(1)
print("""
a: Explorer
b: Regarder l'inventaire
""")
carsaction(["a","b"])
if carsaction(["a"]) == "a":
time.sleep(3)
print("Vous voulez donc explorer.")
time.sleep(3)
[code after...]
else:
print("Test")
instructions
is a list, so you should use if commande.lower() in instructions
For the same reason, the criterion in your while
won't ever be false (even though with the break
statement, it's actually useless). while commande.lower() not in instructions:
would be better.
You could try something like this:
def carsaction(*instructions):
"""
Fonction servant à faire un choix pour interagir avec soi même.
"""
commande = str(None)
while commande.lower() not in instructions:
commande = str(input("Quelle action choisissez-vous?"))
if commande.lower() in instructions:
break
else:
print("Réponse non valide!")
continue
You should pass a list as a parameter containing the valid characters as elements, and make your while loop check if the user input is one of your valid characters in your list, but your code tries to match the whole function parameters with the input rather than only one or more.
To solve this, you should create a list as a parameter and use in
operator when defining the check loop.
def carsaction(instructions):
"""
Fonction servant à faire un choix pour interagir avec soi même.
"""
user_input = str(None)
while user_input not in instructions:
user_input = input("Your input: ")
if user_input in instructions:
break
else:
print("not valid")
continue
carsaction(["a","b","c"])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.