Python Exercise: Guess a number between 1 to 9
3. Number Guessing Game
Write a Python program to guess a number between 1 and 9.
Note : User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct, on successful guess, user will get a "Well guessed!" message, and the program will exit.
Sample Solution:
Python Code:
# Import the 'random' module to generate random numbers
import random
# Generate a random number between 1 and 10 (inclusive) as the target number
target_num, guess_num = random.randint(1, 10), 0
# Start a loop that continues until the guessed number matches the target number
while target_num != guess_num:
# Prompt the user to input a number between 1 and 10 and convert it to an integer
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
# Print a message indicating successful guessing once the correct number is guessed
print('Well guessed!')
Sample Output:
Guess a number between 1 and 10 until you get it right : 5 Well guessed!
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program that randomly selects a number between 1 and 9 and repeatedly prompts the user until the correct guess is made.
- Write a Python program to implement a number guessing game with a maximum number of attempts and hints for higher or lower.
- Write a Python program to create a guessing game where the program gives feedback on how close the guess is to the target.
- Write a Python program that logs the number of guesses made and congratulates the user once the correct number is guessed.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to convert temperatures to and from celsius, fahrenheit.
Next: Write a Python program to construct the following pattern, using a nested for loop.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.