test.py
Python/01_beginner_level/test.py
import random
def number_guessing_game(): # a simple number guessing game
"""A simple number guessing game."""
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
print(f"You have {max_attempts} attempts to guess it!")
while attempts < max_attempts:
try:
guess = int(input(f"\nAttempt {attempts + 1}: Enter your guess: "))
attempts += 1
if guess == secret_number:
print(f"Congratulations! You guessed it in {attempts} attempts!")
break
elif guess < secret_number:
print("Too low! Try a higher number.")
else:
print("Too high! Try a lower number.")
except ValueError:
print("Please enter a valid number!")
attempts -= 1 # Don't count invalid attempts
if attempts >= max_attempts:
print(f"Game over! The secret number was {secret_number}")
if __name__ == "__main__":
number_guessing_game()
Articoli correlati
01_getting_started.py
01_getting_started.py — python source code from the Python learning materials (Python/01_beginner_level/01_getting_started.py).
Leggi l'articolo →02_core_syntax.py
02_core_syntax.py — python source code from the Python learning materials (Python/01_beginner_level/02_core_syntax.py).
Leggi l'articolo →03_control_flow.py
03_control_flow.py — python source code from the Python learning materials (Python/01_beginner_level/03_control_flow.py).
Leggi l'articolo →04_data_structures.py
04_data_structures.py — python source code from the Python learning materials (Python/01_beginner_level/04_data_structures.py).
Leggi l'articolo →05_functions.py
05_functions.py — python source code from the Python learning materials (Python/01_beginner_level/05_functions.py).
Leggi l'articolo →06_error_handling.py
06_error_handling.py — python source code from the Python learning materials (Python/01_beginner_level/06_error_handling.py).
Leggi l'articolo →