I am trying to write a number guessing program as follows:
def oracle():
n = ' '
print 'Start number = 50'
guess = 50 #Sets 50 as a starting number
n = raw_input("\n\nTrue, False or Correct?: ")
while True:
if n == 'True':
guess = guess + int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'False':
guess = guess - int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'Correct':
print 'Success!, your number is approximately equal to:', guess
oracle()
What I am trying to do now is get this sequence of if/ elif/ else commands to loop until the user enters 'Correct', i.e. when the number stated by the program is approximately equal to the users number, however if I do not know the users number I cannot think how I could implement and if statement, and my attempts to use 'while' also do not work.
As an alternative to @Mark Byers' approach, you can use while True
:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Your code won't work because you haven't assigned anything to n
before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break
:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input
in Python 2.x reads a line of input and then evaluates it. You want to use raw_input
.
Note: In Python 3.x, raw_input
has been renamed to input
and the old input
method no longer exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With