Search code examples
pythongoto

Alternative to Goto Label in Python?


I know I can't use Goto and I know Goto is not the answer. I've read similar questions, but I just can't figure out a way to solve my problem.

So, I'm writing a program, in which you have to guess a number. This is an extract of the part I have problems:

x = random.randint(0,100)    

#I want to put a label here

y = int(raw_input("Guess the number between 1 and 100: "))

if isinstance( y, int ):
    while y != x:
        if y > x:
            y = int(raw_input("Wrong! Try a LOWER number: "))
        else:
            y = int(raw_input("Wrong! Try a HIGHER number "))
else:
    print "Try using a integer number"
    #And Here I want to put a kind of "goto label"`

What would you do?


Solution

  • There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore break and continue. Here's one possible solution:

    import random
    
    x = random.randint(1, 100)
    
    prompt = "Guess the number between 1 and 100: "
    
    while True:
        try:
            y = int(raw_input(prompt))
        except ValueError:
            print "Please enter an integer."
            continue
    
        if y > x:
            prompt = "Wrong! Try a LOWER number: "
        elif y < x:
            prompt = "Wrong! Try a HIGHER number: "
        else:
            print "Correct!"
            break
    

    continue jumps to the next iteration of the loop, and break terminates the loop altogether.

    (Also note that I wrapped int(raw_input(...)) in a try/except to handle the case where the user didn't enter an integer. In your code, not entering an integer would just result in an exception. I changed the 0 to a 1 in the randint call too, since based on the text you're printing, you intended to pick between 1 and 100, not 0 and 100.)