python - While loops, if-else statements: Guess my number game -
i'm beginner using python, , writing "guess number game". far have working fine. computer picks random number between 1 , 3 , asks player guess number. if guess higher random number, program prints "lower", , vice versa. player has 5 tries, , when run out, player gets message , game ends. if player guesses correctly, congratulated , game ends. however, when number guessed correctly, program doesn't print congratulatory message , can't figure out why...
import random print("\twelcome 'guess number'!:") print("\ni'm thinking of numer between 1 , 100.") print("guess carefully, have 5 tries!.\n") #sets initial values the_number = random.randint(1,3) guess = int(input("take guess: ")) tries = 1 guesses = 4 #guessing loop while guess != the_number: if guess > the_number: print("lower...") elif guesses <= 0: print("sorry, you're out of guesses! try again...") break elif guess < the_number: print("higher...") guess = int(input("take guess: ")) tries += 1 guesses -= 1 if guess == the_number: print("you guessed it! number was", the_number) print("and took you", tries, "tries!\n")
to answer original question lack of congratulatory message correct number, end code input(), ensure not terminate before displaying last message.
order of calculation:
- give input guess
- reduce guesses (starting @ 5), increase tries (starting @ 1)
- immediate break if guesses == 0
- evaluate guess (lower, higher or equal, end while loop)
import random print("\twelcome 'guess number'!:") print("\ni'm thinking of numer between 1 , 3.") print("guess carefully, have 5 tries!.\n") #sets initial values the_number = random.randint(1,3) guess = int(input("take guess: ")) tries = 1 guesses = 5 #guessing loop while guess != the_number: tries += 1 guesses -= 1 if guesses == 0: print("sorry, you're out of guesses! try again...") break elif guess > the_number: print("lower...") elif guess < the_number: print("higher...") guess = int(input("take guess: ")) if guess == the_number: print("you guessed it! number was", the_number) print("and took you", tries, "tries!\n") input()
Comments
Post a Comment