Search code examples
pythonloops

how to make a python loop


I need help with a python loop. I tried this:

yes=1
play = yes
if play == yes:
    import os
    import random
    import time
    n = random.randint(1,10)
    g = 0
    time.sleep(.25)
    print ("guess the number 1-10")
    time.sleep(.5)
    while g != n:
        g = int ( input ( "what is your guess " ))
        if g < n:
            print ("too low guess again")
        if g > n:
            print (" too high guess again")
        print ("you got the number")
    play = input  ("play again? ")
    time.sleep(.5)
    os.system(clear)

Can anyone help me?

I'm new to python so I'm having trouble with getting it to have it so if you get the number correct then say yes to play again it clears then loops.


Solution

  • You need an outer while loop to play the game again and again

    import os
    import random
    import time
    
    play = "yes"
    while play == "yes":
        n = random.randint(1, 10)
        g = 0
        time.sleep(.25)
        print("guess the number 1-10")
        time.sleep(.5)
        while g != n:
            g = int(input("what is your guess ?"))
            if g < n:
                print("too low guess again")
            elif g > n:
                print(" too high guess again")
            else:
                print("you got the number")
        play = input("play again? ('yes' to continue) ")
        time.sleep(.5)
        os.system("clear")
    

    It may be easier to understand if you break your code with a function

    def one_run():
        n = random.randint(1, 10)
        g = 0
        print("guess the number 1-10")
        while g != n:
            g = int(input("what is your guess ?"))
            if g < n:
                print("too low guess again")
            elif g > n:
                print(" too high guess again")
            else:
                print("you got the number")
    
    play = "yes"
    while play == "yes":
        one_run()
        play = input("play again? ('yes' to continue) ")
        time.sleep(.5)
        os.system("clear")