Python Forum
Help with 'while' loop! Python 3 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Help with 'while' loop! Python 3 (/thread-12610.html)



Help with 'while' loop! Python 3 - rafaelssouzza - Sep-03-2018

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()



RE: Help with 'while' loop! Python 3 - Mekire - Sep-03-2018

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.


RE: Help with 'while' loop! Python 3 - woooee - Sep-03-2018

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':