How To Write a Number Guessing Game in Python

By Tanner Abraham •  Updated: 06/01/21 •  1 min read

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))

Tanner Abraham

Data Scientist and Software Engineer with a focus on experimental projects in new budding technologies that incorporate machine learning and quantum computing into web applications.

Keep Reading