File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Number Guessing Game
2
+ # This program generates a random number and asks the player to guess it.
3
+ # It provides feedback on whether the guess is too high or too low until the correct number is guessed.
4
+
5
+ import random
6
+
7
+ def guess_number ():
8
+ # Generate a random number between 1 and 100 (inclusive)
9
+ secret_number = random .randint (1 , 100 )
10
+
11
+ attempts = 10 # Initialize the number of attempts
12
+
13
+ print ("Welcome to the Number Guessing Game!" )
14
+ print ("I'm thinking of a number between 1 and 100." )
15
+
16
+ while True :
17
+ try :
18
+ # Ask the player for their guess
19
+ guess = int (input ("Guess the number: " ))
20
+
21
+ # Increment the number of attempts
22
+ attempts += 1
23
+
24
+ if guess < secret_number :
25
+ print ("Too low! Try again." )
26
+ elif guess > secret_number :
27
+ print ("Too high! Try again." )
28
+ else :
29
+ print (f"Congratulations! You guessed the number { secret_number } in { attempts } attempts!" )
30
+ break # Exit the loop if the guess is correct
31
+
32
+ except ValueError :
33
+ print ("Invalid input. Please enter a valid number." )
34
+
35
+ if __name__ == "__main__" :
36
+ guess_number ()
You can’t perform that action at this time.
0 commit comments