Write A Python Program To Guess A Number Between 1 To 9

Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program To Guess A Number Between 1 To 9

 

Title : 

Write A Python Program To Guess A Number Between 1 To 9



Write A Python Program To Guess A Number Between 1 To 9


 

Description : 

Hi guys, in this article you will learn a python program that generates random numbers and asks the user to guess the given number. Import the required random library and take a target variable and generate a random integer between 1 and 9.


    
import random

target_number = random.randint(1, 9)


    


Now use the infinite while loop, take a variable named as choice and as the user to guess the number between 1 and 9. Use the if else statements to check if the given user input is less than the target random value print of message appropriately. Check if the choice is greater than the target random value is so print the user choice is greater than target value. if the choice is equal to the target value then use the else block to print the congratulations message that the user has guessed the correct value.


    
while True:
   choice = int(input("Guess a number between 1 to 9: "))

   if choice < target_number:
       print("Too low, try again!")
   elif choice > target_number:
       print("Too high, try again!")
   else:
       print("Congratulations! You guessed the number correctly!")
       exit(0)


    




Complete Python Code : 


    
import random

target_number = random.randint(1, 9)
while True:
   choice = int(input("Guess a number between 1 to 9: "))

   if choice < target_number:
       print("Too low, try again!")
   elif choice > target_number:
       print("Too high, try again!")
   else:
       print("Congratulations! You guessed the number correctly!")
       exit(0)


    

 

 

Output : 


    
Guess a number between 1 to 9: 5
Too high, try again!
Guess a number between 1 to 9: 3
Too low, try again!
Guess a number between 1 to 9: 2
Too low, try again!
Guess a number between 1 to 9: 4
Congratulations! You guessed the number correctly!


    

 

Output : 


    
Guess a number between 1 to 9: 8
Too high, try again!
Guess a number between 1 to 9: 5
Too high, try again!
Guess a number between 1 to 9: 2
Congratulations! You guessed the number correctly!


    



Conclusion :

The above Python program You just random module to generate random integer between 1 and 9. Using the infinite while loop the program asks the user to enter his choice between one and nine and compare it with the generated random value. The program prints appropriate message If the value is less than are greater than or equals to the random value Comment it down below if you have any suggestions to improve the above Python program

 

Post a Comment

0 Comments