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.

0

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

5 Comments

+1 similar to my update. I think the use of input here is also wrong.
@MarkByers: changed it to raw_input. From the looks of the print statements, the OP is using Python 2.
Could either of you tell me why the code now terminates after entering True or False?
Err... perhaps because you put a break statement there?! What exactly did you think would happen when it hit the break statement? Perhaps you should read a Python tutorial...
Sorry I'm being stupid, I have been up for too long haha, thanks for the help :)
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.

2 Comments

+1, though it would be more pythonic to use None to denote "no value".
Could either of you tell me why the code now terminates after entering True or False?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.