Python @ DjangoSpin

PyPro #4 Guess the Number

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Guess the Number in Python

Guess the Number in Python

Python code for the famous game Guess the Number. Ask the player to guess a number between 1 and 100 in 7 tries. After each incorrect guess, advise the player to aim lower or higher, and tell the player how many tries he is left with.

## Guess the number
## The program picks a random number between 1 & 100. It then prompts the user for a guess. After each incorrect guess, the program advises the player to try higher or lower, and tells him/her how many tries are left.
import random

print("I have chosen a random number between 1 & 100.")

number = random.randint(1, 101)

tries = 0
guess = 0

while True:
    guess = int(input("Enter your guess: "))
    
    # if the guess is correct
    if guess == number:
        print("You have correctly guessed the number.")
        break
    
    # if the guess is not correct
    else:
        # record the try
        tries = tries + 1
        # if the user has tries left
        if tries < 7:
            # if the guess was higher than the number
            if guess > number:
                print("Oops! Try lower. You have", 7 - tries, "chances left.")
            # if the guess was lower than the number
            else:
                print("Oops! Try higher. You have", 7 - tries, "chances left.")
        # if the user has run out of tries i.e. tries == 7
        else:
            print("You have run out of guesses. The number was:", number)
            break
Try it online here.

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply