How To Write a Number Guessing Game in Python

Watch Video

Python Code

#Guess the number game

import random
secret_number = random.randint(1,21)
print('Hi, what is your name?')
name = input('Enter your name here: ')
print(f'{name}, would you like to play a game?')
print(f'Well, {name} I am thinking of a number between 1 and 20. Can you guess what it is?')

for guess_taken in range(1,7):
    print('Take a guess ')
    guess = int(input())

    if guess < secret_number:
        print('Your guess is too low!')
    elif guess > secret_number:
        print('Your guess is too high!')
    elif guess <= 0:
        print('Out of bounds! That is not a valid number.')
    else:
        break 

if guess == secret_number:
    print(f'Good Job {name} you guessed the number I was thinking of in ' + str(guess_taken) + ' turns.')
else:
    print('Nope. The number I was thinking of was ' + str(secret_number))

Leave a Comment

Your email address will not be published. Required fields are marked *