| 2 | |
| 3 | |
| 4 | def number_guessing_game(): |
| 5 | secret_number = random.randint(1, 100) |
| 6 | attempts = 0 |
| 7 | |
| 8 | print("Welcome to the Number Guessing Game!") |
| 9 | print("I'm thinking of a number between 1 and 100.") |
| 10 | |
| 11 | while True: |
| 12 | try: |
| 13 | guess = int(input("Your guess: ")) |
| 14 | attempts += 1 |
| 15 | |
| 16 | if guess < secret_number: |
| 17 | print("Too low! Try again.") |
| 18 | elif guess > secret_number: |
| 19 | print("Too high! Try again.") |
| 20 | else: |
| 21 | print( |
| 22 | f"Congratulations! You guessed the number {secret_number} in {attempts} attempts!" |
| 23 | ) |
| 24 | break |
| 25 | |
| 26 | except ValueError: |
| 27 | print("Please enter a valid number.") |
| 28 | |
| 29 | |
| 30 | if __name__ == "__main__": |