Home > other >  Python Multi Answer loop
Python Multi Answer loop

Time:01-16

I need help adding a loop to the 'else' section so that it re-asks the question if it doesn't understand. Here is the code.

answer = raw_input("What did you think of this program?")

is answer = 'yes':
print("Thank you! Have a nice day.")

elif answer = 'no':
print("Thank you for your feedback, I will try to improve this program")

else:
print("Sorry I don't understand, please try again.")

CodePudding user response:

Put the whole thing inside a while loop, and break out of the loop if they answer yes or no.

while True:
    answer = raw_input("What did you think of this program?")

    if answer == 'yes':
        print("Thank you! Have a nice day.")
        break

    elif answer == 'no':
        print("Thank you for your feedback, I will try to improve this program")
        break

    else:
        print("Sorry I don't understand, please try again.")

CodePudding user response:

You can try to wrap the logic with a function and call it recursively.

You have some syntax errors (single equal signs and 'is' instead of 'if' etc) but below you can find corrected code

def get_answer():

    answer = input("What did you think of this program?")
    
    if answer == 'yes':
      print("Thank you! Have a nice day.")
    
    elif answer == 'no':
      print("Thank you for your feedback, I will try to improve this program")
    
    else:
      print("Sorry I don't understand, please try again.")
      get_answer()

get_answer()

Working repl.it project: https://replit.com/@HarunYilmaz1/AutomaticLightheartedDoom#main.py

CodePudding user response:

isAnswered = False
while not isAnswered:
    answer = input("What did you think of this program?")
    if answer == 'yes':
        print("Thank you! Have a nice day.")
        isAnswered = True
    elif answer == 'no':
        print("Thank you for your feedback, I will try to improve this program")
        isAnswered = True
    else:
        print("Sorry I don't understand, please try again.")
    
    
  •  Tags:  
  • Related