-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumber_guessing_game.py
More file actions
63 lines (48 loc) · 1.72 KB
/
number_guessing_game.py
File metadata and controls
63 lines (48 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# Number Guessing Game
# Count attempts only for valid numbers
import random
print("🎯 Welcome to Number Guessing Game")
print("----------------------------------")
print("Choose Difficulty Level:")
print("1. Easy (1 - 10)")
print("2. Medium (1 - 50)")
print("3. Difficult (1 - 100)")
# Select difficulty and number
while True:
level = input("Enter choice (easy / medium / difficult): ").lower()
if level == "easy":
number = random.randint(1, 10)
max_range = 10
break
elif level == "medium":
number = random.randint(1, 50)
max_range = 50
break
elif level == "difficult":
number = random.randint(1, 100)
max_range = 100
break
else:
print("❌ Invalid choice. Try again.\n")
print("\n🎮 Game Started! Guess the number.\n")
attempts = 0 # Counts only valid guesses
while True:
try:
guess = int(input(f"Enter a number (1 to {max_range}): "))
# Check if guess is within range
if guess < 1 or guess > max_range:
print(f"⚠️ Please enter a number between 1 and {max_range}\n")
continue # Skip incrementing attempts
# Valid guess, increment attempts
attempts += 1
# Compare guess
if guess == number:
print(f"🎉 Congratulations! You guessed the number in {attempts} attempts.")
break
elif guess > number:
print("📈 Too high! Try again.\n")
else:
print("📉 Too low! Try again.\n")
except ValueError:
print("❌ Invalid input! Please enter a valid integer.\n")
# Invalid input, do not increment attempts