Create A Simple Python Program To Guess A Number
Step-by-Step Guide to Python Number Guessing Game
First, import the 'random' module and import 'logo', which is used to contain the word art or logo. Then, fix the global variables.
logo=r"""
______ __ __ __
/ ____/_ _____ __________ / /_/ /_ ___ ____ __ ______ ___ / /_ ___ _____
/ / __/ / / / _ \/ ___/ ___/ / __/ __ \/ _ \ / __ \/ / / / __ `__ \/ __ \/ _ \/ ___/
/ /_/ / /_/ / __(__ |__ ) / /_/ / / / __/ / / / / /_/ / / / / / / /_/ / __/ /
\____/\__,_/\___/____/____/ \__/_/ /_/\___/ /_/ /_/\__,_/_/ /_/ /_/_.___/\___/_/ """
import random
import logo
easy=10 #global variable
hard=5 #global variable
Create a Function 'dificulty_lvl' ,which is used to check the level of the difficulty of the game.
def dificulty_lvl(lvl):
if lvl == 'easy':
return easy
else:
return hard
Create a Function 'check' , which is used to compare the user guesses to the actual answer if it is low or high or right .
def check(user_guess,ans,attempt):
# while attempt-1!=0:
if user_guess < ans:
print("Your guess is too low")
return attempt-1
# print(f"You have {attempt-1} attempts remaining to guess the number.")
elif user_guess>ans:
print("Your guess is too high.")
return attempt-1
# print(f"You have {attempt-1} attempts remaining to guess the number.")
else:
print(f"Your guess is right....The answer is {ans}")
# break
Create a function 'play'. It is the main function of the game. The user is given a limited number of attempts based on the selected difficulty level. If the user fails to guess the number within the given attempts, they will lose the game..
def play():
print(logo.logo)
print("Let me think of a number between 1 to 50.")
ans=random.randint(1,50)
# print(ans)
lvl=input("Choose level of difficulty....Type 'easy' or 'hard'.").lower()
attempt=dificulty_lvl(lvl)
user_guess=0
while user_guess!=ans:
print(f"You have {attempt} remaining to guess the number!")
user_guess=int(input("Make a Guess:"))
attempt=check(user_guess,ans,attempt)
if attempt==0:
print("You are out of guesses. You lose..... Better luck next time.....")
# return
break
elif user_guess!=ans:
print("Guess again")
Start the game using play function.
play()