سؤال

In this piece of code I am looking for a input:

mode = input("Generate S1(0) or S2(1)?\n")
if mode == "0":
    mode = "S1"
elif mode == "1":
    mode = "S2"
else:
    print("Mode not recogised!")

for being able to handle error better (mode>1), i.e. when if hit the else condition, I want the code to ask the input again.

Any idea how i can do that or which function I am looking for?

هل كانت مفيدة؟

المحلول

mode = None
while not mode:
    answer = input("Generate S1(0) or S2(1)?\n")
    if answer == "0":
        mode = "S1"
    elif answer == "1":
        mode = "S2"
    else:
        print("Mode not recogised!")

نصائح أخرى

This is bit tricky. But you can do like this.

while 1:
    mode = input("Generate S1(0) or S2(1)?\n")
    if mode == "0":
        mode = "S1"
    elif mode == "1":
        mode = "S2"
    else:
        print("Mode not recogised!")
        continue
    break
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top