number-guessing-game-in-python

Python Example 1 – Number guessing game with python

Hello World, Welcome to projectsplaza.com. Today we will discuss how to create a number guessing game with python. This tutorial is for python beginner. Python has three different numeric types: int, float, and complex. Most of the time, it is enough to know about int(for the whole number) and float(for fraction number). For this game, we will do the following steps

  • Write a function guess_number that takes no arguments.
  • When we run this function it will automatically choose the number between 0-50.
  • Ask the user to guess what number has been chosen.
  • Every time user guess a number, we will indicate the following:
    • Too High
    • Too Low
    • Just Right
  • If the user guesses the correct number then the program exit, otherwise the user is asked to try again.
  • Programm will exist only if the user guesses the correct number.

We will use randint to generate a random number from a defined range.

import random
def guess_number():
    answer=random.randint(0,50)
    while True:
        user_guess=int(input('Guess the number: '))

        if(user_guess>answer):
            print(f'You guess {user_guess} is too high ')
        if(user_guess<answer):
            print(f'You guess {user_guess} is too low ')
        else:
            print(f'Awesome! The answer is {user_guess}')        
guess_number()

 

Leave a Reply

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