Number Guessing Game in Python
This is a simple beginner mini project using:
randommodulewhileloopif-elif-elseconditionsuser input
The computer selects a random number, and the user tries to guess it.
Python Code
import random
# Computer chooses a random number between 1 and 10
secret_number = random.randint(1, 10)
print("Welcome to Number Guessing Game!")
print("Guess a number between 1 and 10")
while True:
guess = int(input("Enter your guess: "))
if guess == secret_number:
print("Congratulations! You guessed the correct number.")
break
elif guess < secret_number:
print("Too low! Try again.")
else:
print("Too high! Try again.")
Step-by-Step Explanation
1. Import Random Module
import random
This helps Python generate random numbers.
2. Generate Random Number
secret_number = random.randint(1, 10)
This creates a random number between 1 and 10.
Example:
It may generate:
7
but the user cannot see it.
3. Display Instructions
print("Guess a number between 1 and 10")
This tells the player what to do.
4. Infinite Loop
while True:
This keeps asking until the correct answer is guessed.
5. User Input
guess = int(input("Enter your guess: "))
User enters a number.
6. Check Correct Guess
if guess == secret_number:
If correct → success message + loop stops.
7. Too Low
elif guess < secret_number:
If entered number is smaller.
8. Too High
else:
If entered number is greater.
Sample Output
Welcome to Number Guessing Game!
Guess a number between 1 and 10
Enter your guess: 4
Too low! Try again.
Enter your guess: 8
Too high! Try again.
Enter your guess: 6
Congratulations! You guessed the correct number.
Short Version
import random
n = random.randint(1, 10)
while True:
g = int(input("Guess: "))
if g == n:
print("Correct!")
break
elif g < n:
print("Low")
else:
print("High")
Viva Questions
Q: Why do we use random module?
To generate random numbers.
Q: What does randint(1,10) mean?
It generates a random integer between 1 and 10.
Q: Why do we use while True?
To keep repeating until the correct answer is guessed.
Q: Why do we use break?
To stop the loop after correct guessing.


No comments:
Post a Comment