-3

python,please help. I want this code to ask someone if they are ok with the grade. if they say yes, it prints good! if they say no, it says oh well! if they dont say yes or no, i want it to print " please enter yes or no" and keep asking them that until they finally say yes or no. This is what i have so far and when i run it and DONT type yes or no, it spams "please enter yes or no" millions of time

theanswer= raw_input("Are you ok with that grade?")
while theanswer:
    if theanswer == ("yes"):
        print ("good!")
        break
    elif theanswer == ("no"):
        print ("oh well")
        break
    else: 
        print "enter yes or no"

what do i need to do so that it works, ive been trying a lot

4 Answers4

7

You need to have a blocking call in your else statement. Otherwise you will have an infinite loop because theanswer will always be true. Like asking for input:

theanswer= raw_input("Are you ok with that grade?")
while theanswer:
    if theanswer == ("yes"):
        print ("good!")
        break
    elif theanswer == ("no"):
        print ("oh well")
        break
    else: 
        theanswer= raw_input("Please enter yes or no")

Here is a good resorce on Blocking vs Non-Blocking I/O. It's an important fundamental in any application.

Community
  • 1
  • 1
asdf
  • 2,927
  • 2
  • 21
  • 42
  • @EvanWestphal please try and take this as a learning experience. Here's a good resource on [Blocking vs Non-Blocking I/O](http://stackoverflow.com/questions/1241429/blocking-io-vs-non-blocking-io-looking-for-good-articles). It'll be good to understand the difference in a future coding career :) – asdf Sep 02 '15 at 20:18
  • @EvanWestphal Also, if this worked for you, please select it as the accepted solution :) – asdf Sep 02 '15 at 20:22
3

or this (this separates the input logic from what you do with the answer):

theanswer = raw_input("Are you ok with that grade?")
while theanswer not in ('yes', 'no'):
    theanswer = raw_input('Please enter yes or no')

if theanswer == "yes":
    print("good!")
elif theanswer == "no":
    print("oh well")
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
1

Basically in your code you have a while loop running that will only break if theanswer == yes or == no. You are also not giving the possibility of changing the value of theanswer in your loop therefore => infinity loop.

add this to your code:

else: 

        print "enter yes or no"
        theanswer= raw_input("Are you ok with that grade?")
Ryan
  • 2,167
  • 2
  • 28
  • 33
0

This can be accomplished with recursion

def get_user_input(text):
    theanswer= raw_input(text)
    if theanswer == 'yes':
        print('good!')
    elif theanswer == ("no"):
        print('oh well')
    else: 
        get_user_input('enter yes or no')

get_user_input('Are you ok with that grade?')
Cody Bouche
  • 945
  • 5
  • 10