10

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
George Burrows
  • 3,391
  • 9
  • 31
  • 31

2 Answers2

19

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.
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
2

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452