简体   繁体   中英

Breaking a loop for basic python

I have been working on this for a while now. I have been able to get parts of this to work, but never the whole thing. The end goal is to loop the user back into another game if they so choose. I think the issue is with my break statement, but I am not sure how to route around it. I have included all my code so that any mistakes can be found. Apologies if this has already been answered, I couldn't find a page with this kind of problem.

def game():
    import random
    from random import randint
    n = randint(1, 10)
    print('Enter a seed vlaue: ')
    the_seed_value = input(' ')

    random.seed(the_seed_value)

    guessesTaken = 0

    print("what is your name?")
    myName = input("")

    guess = int(input("Enter an integer from 1 to 99: "))

    while n != "guess":


        if guess < n:
            print ("guess is low")
            guessesTaken = guessesTaken + 1
            guess = int(input("Enter an integer from 1 to 99: "))
        elif guess > n:
            print ("guess is high")
            guessesTaken = guessesTaken + 1
            guess = int(input("Enter an integer from 1 to 99: "))
        else:
            print ("Congradulations " + myName +  " you guessed it in " + str(guessesTaken) + " guesses!") 
            break 


    print('Want to play agian? y/n')
    answer = input(" ")
    if answer == "n":
        print ("Ok, See you next time!")

    elif answer == "y":
        print("Starting new game!")
        game()


def main():
    game()

if __name__ == "__main__":
    main()

For one, @kerwei notes correctly that your while line has an issue, and needs to be changed from while n != "guess": to while n != guess: .

For two, your while loop is satisfied when the player guesses correctly, bypassing the Congrats line.

Since the game is currently structured to stay in the loop until the player guesses correctly, a simple fix would be to remove the else: line from the loop and place the victory statement afterwards. That is,

def game()
    ...
    while n != guess:
        if guess < n:
            ...
        elif guess > n:
            ...
    print('Congrats!')
    print('play again?')
    ... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM