0

I'm a beginner at python, currently studying Al Sweigarts "Automate the boring stuff with python" and im making a simple program that responds to you and asks questions, adding to it with each new thing that i learn. I'm trying to have it respond to a yes or no question, and respond accordingly if anything else is said with "please answer with yes or no". however it only responds after i type the answer in multiple times and i don't understand why. Here is the part of the code i'm at now.

print ('I am a computer, so i can calculate much faster, watch this')
print ('the multiplication table of 9 is')
for i in range (9,99,9):
     print (str(i))
print ('I could keep going forever, want me to?')
while input () != 'yes' and input () != 'no':
     print ('Please answer with yes or no')
if input () == 'no':
     print ('okay i will not')
elif input () == 'yes':
     print ('okay i will')
     for i in range (9,3009,9):
          print (str(i))
     print ('okay, that is enough')

Does anyone know what i'm doing wrong? I've only started studying python a few days ago.

1 Answers1

2

Every time you call input() the interpreter will wait for a new input. You need to assign the first call to input() to a variable and then check its value.

print ('I am a computer, so i can calculate much faster, watch this')
print ('the multiplication table of 9 is')
for i in range (9,99,9):
     print (str(i))
print ('I could keep going forever, want me to?')
answer = input()
while answer != 'yes' and answer != 'no':
     print ('Please answer with yes or no')
if answer == 'no':
     print ('okay i will not')
elif answer == 'yes':
     print ('okay i will')
     for i in range (9,3009,9):
          print (str(i))
     print ('okay, that is enough')


However, this introduces an infinite loop if the user inputs anything other than yes or no.

To remedy this, see Asking the user for input until they give a valid response

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Thanks for the fast response! I really appreciate it! – Lucas Small Dec 20 '17 at 12:32
  • 1
    You need to include another `answer = input()` inside the loop to prevent the infinite loop by asking until the answer is yes or no. Also you can check in a more pythonic way doing `while answer not in ['yes', 'no']:` –  Dec 20 '17 at 12:34