Python Forum

Full Version: Help with 'while' loop! Python 3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good night, mates. I need some help

I need to develop an algorithm that generates a number between 1 and 10, asks me to try to guess it and tells me if its too high or too low, and if i get it right is offers me another random until i write "quit".
So far i've done this, but the part where it should offer me a new random number is not working. Also the secure word "quit" doesnt break the loop.
I've tried many combinations, but i just can't fix the mistake.



import random

def startgame():

    while b != 'quit':
        b = 0
        a = random.randint (1,10)
        cont = 0

        while True:
            b = input("Guess a number: ")
            if b == 'quit':
                break
            elif int(b) > a:
                print("Too high!")
                cont += 1
            elif int(b) < a:
                print ("Too low!")
                cont += 1
            elif int(b) == a:
                print ("You got it right!")
                print ('You needed ',cont,'guesses!')
                False

startgame()
That dangling False doesn't do anything. You can either use break to exit that loop or set some variable.
run = True
while run:
    #stuff
    elif a == b:
        run = False
You also need to ask the player if they want to play again (or type 'quit').
I strongly suggest more meaningful variable names so that the code is clearer as well.
For instance ashould be target and b should be guess. Anything to make the code more obvious than a and b.
What version of Python are you using. If it is Python2.X, input will only grab numbers and "quit" will never equal a number. Also, the program will produce an error on this line because b has not been declared on the first pass
while b != 'quit':