-
Notifications
You must be signed in to change notification settings - Fork 157
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #209 from shiveshhhhsingh1723/patch-1
Create Guess the number game
- Loading branch information
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import random | ||
|
||
def number_guessing_game(): | ||
# Generate a random number between 1 and 100 | ||
number_to_guess = random.randint(1, 100) | ||
attempts = 0 | ||
print("Welcome to the Number Guessing Game!") | ||
print("I have picked a number between 1 and 100.") | ||
print("Can you guess what it is?") | ||
|
||
while True: | ||
# Ask the player for a guess | ||
player_guess = input("Enter your guess: ") | ||
|
||
try: | ||
# Convert the guess to an integer | ||
player_guess = int(player_guess) | ||
except ValueError: | ||
print("Please enter a valid number.") | ||
continue | ||
|
||
attempts += 1 | ||
|
||
# Check the player's guess | ||
if player_guess < number_to_guess: | ||
print("Too low! Try again.") | ||
elif player_guess > number_to_guess: | ||
print("Too high! Try again.") | ||
else: | ||
print(f"Congratulations! You've guessed the number in {attempts} attempts.") | ||
break | ||
|
||
# Start the game | ||
number_guessing_game() |