What is Python?
Python is an interpreted, high-level, general-purpose programming language. It’s one of the most widely used languages in the world thanks to its clear, readable syntax, which makes it ideal for beginners. It’s used in web development, data science, automation, artificial intelligence, and much more.
How to run Python
First, install Python from python.org. During installation, check the “Add Python to PATH” option. To run a file, open a terminal/command prompt, navigate to the folder where your .py file is located, and type:
python file_name.py
You can also use editors like VS Code or PyCharm, which let you run code with a button.
The “Guess the Number” game
The computer chooses a secret number from 1 to 10 and the user tries to guess it. It’s a classic exercise to practice variables, conditionals, and loops.
Importing the random module
To generate random numbers we use the random module:
import random
secret_number = random.randint(1, 10)
Main loop with input
A while loop keeps the game running until the user guesses correctly. Inside the loop we ask for a number with input() and convert it to an integer:
while playing:
try:
user_guess = int(input("Guess a number from 1 to 10: "))
# ... validations and comparisons
except ValueError:
print("Enter an integer from 1 to 10.")
Conditionals and feedback
Depending on the distance between the user’s number and the secret one, we provide “Warm” or “Cold” hints:
difference = abs(user_guess - secret_number)
if difference == 0:
print("Correct!")
playing = False
elif difference <= 5:
print("Warm")
else:
print("Cold")
Error handling with try/except
If the user types text instead of a number, int() raises ValueError. We catch it with try/except to prevent the program from crashing.
