Python becomes easier when you run a small program, change it, and see what happens. This guide takes you from your first lines to a working calculator, with complete examples, expected results, and exercises you can solve yourself.
Python · your first three lines
name = "Maya"
hours = 4
print(f"{name} practiced Python for {hours} hours.")
Output
Maya practiced Python for 4 hours.
The first two lines give names to values. The last line displays a sentence. The f before the quoted string lets Python insert values inside braces. Change the name or number and run it again: you have already changed a program's behavior.
1. Set up Python and run a file
Install a supported Python 3 release from python.org, following the instructions for your operating system. You need an interpreter, which runs Python, and an editor, which saves your code. Thonny is one approachable option; an editor you already know is also fine. You do not need to choose a web framework or install a machine-learning library to begin.
Create a folder called python-practice. Save the three lines above in a plain-text file named hello.py inside it. Open a terminal in that folder. The command depends on your installation:
| System | Check Python | Run the file |
|---|
| Windows, with the Python launcher | py --version | py hello.py |
| macOS or Linux | python3 --version | python3 hello.py |
The version command should print a Python 3 version. If the command is not found, check the installation instructions and reopen your terminal. If Python cannot find hello.py, check your current folder and the filename; some editors accidentally save hello.py.txt.
Where to type: shell commands such as python3 hello.py belong in the terminal. Python statements such as print("Hello") belong in a .py file or at Python's interactive >>> prompt. Do not paste a shell command at that prompt. Save each example below as its own file and run it with the command that works on your computer.
Create an isolated environment once
A virtual environment keeps a project's installed packages separate. From your practice folder, use the commands for your shell. These commands create the same folder name, .venv; choose one row, not all three.
| Shell | Create | Activate |
|---|
| Windows Command Prompt | py -m venv .venv | .venv\Scripts\activate.bat |
| Windows PowerShell | py -m venv .venv | .venv\Scripts\Activate.ps1 |
| macOS/Linux bash or zsh | python3 -m venv .venv | source .venv/bin/activate |
After activation, the examples can be run with python filename.py. If PowerShell blocks the activation script, activation is optional: run .venv\Scripts\python.exe hello.py directly. On macOS/Linux, the equivalent is .venv/bin/python hello.py. The venv documentation describes both approaches.
All programs in this guide use Python's built-in features or standard library. No package installation is required. Later, install an external package through the selected interpreter with python -m pip install package_name. Keep .venv/ out of version control; share your source files and a dependency description instead of the environment folder.
2. Store values, read input, and display results
A variable is a name referring to a value. The = operator assigns it; == compares two values. Use descriptive names such as distance_km. Python is case-sensitive: distance and Distance are different names. A comment starts with # and explains code without changing its behavior.
distance_km = 18
hours = 1.5
speed = distance_km / hours
print(type(distance_km).__name__)
print(type(hours).__name__)
print(f"Average speed: {speed:.1f} km/h")
Output
int
float
Average speed: 12.0 km/h
int represents an integer; float represents a floating-point number. type(value).__name__ displays the name of a value's type. The expression after = is evaluated before its result is assigned. The formatting instruction :.1f displays one decimal place. It changes the displayed text, not the value stored in speed.
| Type | Example | Use it for |
|---|
int | 3 | Counts and whole numbers |
float | 2.5 | Measurements and fractional results |
str | "Maya" | Text, including text entered by a user |
bool | True, False | Answers to conditions |
list | [4, 7, 9] | An ordered collection you can change |
dict | {"name": "Maya"} | Values looked up by a key |
Convert input before doing arithmetic
input() displays a prompt and returns text, even when the user types digits. Convert that text with int() for a whole number or float() for a fractional number. Save this as practice.py. When asked, enter 12:
minutes_text = input("Minutes practiced: ")
minutes = int(minutes_text)
print(f"After five more minutes: {minutes + 5}")
Example session · enter 12 and press Enter.
Minutes practiced: 12
After five more minutes: 17
"12" + "5" produces "125" because both operands are strings. Converting the input makes arithmetic possible. Typing twelve in this first version raises ValueError; section 6 shows how to handle that case.
The basic arithmetic operators are +, -, *, and /. Use ** for a power, % for a remainder, and // for floor division. Floor division rounds toward negative infinity: -7 // 2 is -4. Parentheses make the order explicit, as in (2 + 3) * 4.
3. Make decisions with conditions
A condition evaluates to true or false. An if block runs when its condition is true; elif checks another case; else handles what remains. Python uses indentation to group statements. Use four spaces per level, and keep statements in the same block aligned.
minutes = 25
if minutes >= 30:
message = "Daily goal reached."
elif minutes >= 10:
message = "A useful practice session."
else:
message = "Start with one small exercise."
print(message)
Output
A useful practice session.
Only the first matching branch runs. Try minutes = 35 and then minutes = 5. The final print() is outside the branches, so it runs in every case. Each line beginning a block ends with a colon.
Comparisons include ==, !=, <, <=, >, and >=. Combine conditions with and or or, and reverse one with not. For example, minutes >= 10 and minutes <= 60 requires both comparisons to succeed. Start with ordinary conditions before exploring more advanced syntax.
4. Repeat work and organize collections
Use a for loop to visit each item
A list stores an ordered sequence. Its first item is at index 0; its last item can be read with -1. Lists are mutable: append() adds an item, and assignment can replace an item. This complete example totals three practice sessions:
sessions = [15, 20]
sessions.append(10)
total = 0
for minutes in sessions:
total += minutes
print(f"First session: {sessions[0]} minutes")
print(f"Total: {total} minutes")
Output
First session: 15 minutes
Total: 45 minutes
On each pass, minutes receives the next item. total += minutes adds that value to the running total. For this calculation, sum(sessions) would also work; the loop makes the repeated steps visible. Use range(3) when you need the sequence 0, 1, 2: the end value is excluded.
Use a while loop while a condition remains true
remaining = 3
while remaining > 0:
print(f"Attempts remaining: {remaining}")
remaining -= 1
print("Finished.")
Output
Attempts remaining: 3
Attempts remaining: 2
Attempts remaining: 1
Finished.
The update matters. Without remaining -= 1, the condition never changes and this loop does not finish. Later, the calculator uses while True intentionally and exits with break. A continue statement skips the rest of the current pass and starts the next one.
Look up values with a dictionary
learner = {"name": "Maya", "minutes": 45}
learner["minutes"] += 10
print(learner["name"])
print(learner.get("language", "Python"))
print(f"Practice: {learner['minutes']} minutes")
Output
Maya
Python
Practice: 55 minutes
A dictionary associates keys with values. Accessing a missing key with square brackets raises KeyError; get() can supply a default instead. Use a list for a sequence of sessions and a dictionary for a record with named fields.
A tuple, such as (10, 20), is an ordered collection whose slots cannot be reassigned. A set, such as {"python", "testing"}, stores unique values without a defined sequence order. Choose the structure for the operations you need. A tuple can be a dictionary key only when all its elements are hashable; a tuple containing a list cannot. See Python's definition of hashability.
Assignment does not automatically copy a collection: other = sessions gives two names to the same list. For a separate shallow copy, use other = sessions.copy(). Nested mutable objects still need additional care; for now, practice with lists of numbers or strings.
5. Turn repeated steps into functions
A function gives a name to a reusable operation. Define it with def, list its parameters in parentheses, and use return to send a result back to the caller. Here is a complete script:
def minutes_to_hours(minutes):
"""Convert a number of minutes to hours."""
return minutes / 60
first = minutes_to_hours(90)
second = minutes_to_hours(30)
print(f"First session: {first:.1f} hours")
print(f"Second session: {second:.1f} hours")
Output
First session: 1.5 hours
Second session: 0.5 hours
minutes is the parameter; 90 is an argument supplied by the caller. The triple-quoted string is a docstring describing the function. A local name belongs to that function call. Passing a different argument reuses the same logic without copying its body.
return and print() have different jobs. Returning a value lets another calculation use it. Printing displays something for a person. A function that reaches its end without return returns None. Keeping calculation separate from input and display will make the final project easier to check.
6. Handle errors and save a small result
Read a traceback from its final line to identify the error type and message, then find the file and line that caused it. A SyntaxError means Python could not parse the program. A NameError often means a misspelled or undefined name. A ValueError can mean that a conversion received unsuitable text.
Use try and a specific except when a failure is expected and you know how to respond. In this example, enter twelve to exercise the recovery path:
text = input("Minutes practiced: ")
try:
minutes = int(text)
except ValueError:
print("Please enter a whole number, such as 12.")
else:
print(f"Recorded: {minutes} minutes")
Example session
Minutes practiced: twelve
Please enter a whole number, such as 12.
The else block runs only when the conversion succeeds. Catch the exception you expect instead of hiding every failure with a bare except. This version displays an explanation and stops; the calculator will keep asking until it receives a valid number.
Write and read JSON using the standard library
Modules provide code you can import. Python includes json for a common text format and pathlib for file paths. Save and run this complete example from your practice folder:
import json
from pathlib import Path
notes = {"language": "Python", "minutes": 45}
path = Path("practice-notes.json")
path.write_text(json.dumps(notes, indent=2), encoding="utf-8")
loaded = json.loads(path.read_text(encoding="utf-8"))
print(f"Saved practice: {loaded['minutes']} minutes")
Output
Saved practice: 45 minutes
This creates practice-notes.json in the current working folder and replaces that file's contents if you run it again. json.dumps() turns the dictionary into text; json.loads() turns the text back into Python data. Explicit UTF-8 encoding keeps text handling predictable. Open the file in your editor to see what the program saved.
7. Build a calculator you can actually use
The project combines input, conversion, conditions, loops, functions, imports, and error handling. It supports addition, subtraction, multiplication, and division. It accepts one operator and two numbers per calculation, retries invalid numeric input, and keeps running until you enter q at the operator prompt.
Save the complete program below as calculator.py. It has no third-party dependencies.
import math
def read_number(prompt):
"""Keep asking until the user enters a finite number."""
while True:
try:
number = float(input(prompt))
except ValueError:
print("Enter a number, such as 12 or 3.5.")
continue
if not math.isfinite(number):
print("Enter a finite number.")
continue
return number
def calculate(left, operator, right):
"""Calculate one result without reading or printing."""
if operator == "+":
return left + right
if operator == "-":
return left - right
if operator == "*":
return left * right
if operator == "/":
if right == 0:
raise ZeroDivisionError("Cannot divide by zero.")
return left / right
raise ValueError("Unknown operator.")
def main():
print("Calculator: +, -, *, /; q to quit.")
while True:
operator = input("Operator: ").strip().lower()
if operator == "q":
break
if operator not in ("+", "-", "*", "/"):
print("Choose +, -, *, /, or q.")
continue
left = read_number("First number: ")
right = read_number("Second number: ")
try:
result = calculate(left, operator, right)
except ZeroDivisionError as error:
print(error)
continue
if not math.isfinite(result):
print("Result is too large. Try smaller numbers.")
continue
print(f"Result: {result:.12g}")
print("Goodbye!")
if __name__ == "__main__":
main()
Run it · use python calculator.py in the activated environment. Otherwise, use your working py or python3 command.
Calculator: +, -, *, /; q to quit.
Operator: +
First number: 12
Second number: 3.5
Result: 15.5
Operator: /
First number: 8
Second number: 0
Cannot divide by zero.
Operator: q
Goodbye!
Understand the three responsibilities
read_number() handles input. float() converts text, except ValueError handles an unsuccessful conversion, and continue retries. The standard-library function math.isfinite() rejects special values such as nan and inf.calculate() handles arithmetic. It returns a value without asking questions or printing. Division by zero raises a specific exception with a readable message. An unsupported operator raises ValueError, although the interface filters those operators before calling it.main() manages the conversation. It chooses when to ask, retry, display a result, or stop. strip() removes surrounding whitespace, and lower() lets both Q and q exit.
The final if __name__ == "__main__": calls main() when this file is run directly. Importing the file from another script makes its functions available without starting the interactive conversation. This is useful for checking calculations separately.
:.12g displays up to 12 significant digits without unnecessary trailing zeros. Floating-point arithmetic can approximate decimal values; display formatting does not make it exact. This is a learning calculator, and it does not parse complete expressions such as 2 + 3 * 4. Its prompts deliberately request one operation at a time.
Check successful and unsuccessful inputs
| Try this | Expected behavior |
|---|
+, 12, 3.5 | Displays 15.5 |
-, 3, 8 | Displays -5 |
*, 6, 7 | Displays 42 |
/, 7, 2 | Displays 3.5 |
/, 8, 0 | Explains the error and asks for another operator |
banana at a number prompt | Asks for that number again |
nan or inf at a number prompt | Requests a finite number |
? at the operator prompt | Shows the supported choices |
q at the operator prompt | Exits with Goodbye! |
Testing an error path is part of finishing a program. First confirm ordinary calculations. Then deliberately give it something unexpected and check that it responds as described. Change one part at a time, save the file, and rerun the same cases.
8. Practice before looking at the solutions
These exercises use only concepts already introduced. Write each as a separate script. Predict the result, run your version, then open the solution to compare approaches. A different implementation is fine when it meets the same requirements.
Exercise 1 · Convert a temperature
Write celsius_to_fahrenheit(celsius) using celsius * 9 / 5 + 32. Return the result. Call it for 0 and 25; display 32.0 and 77.0 on separate lines.
Show solution: temperature conversion
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
print(f"{celsius_to_fahrenheit(0):.1f}")
print(f"{celsius_to_fahrenheit(25):.1f}")
Output
32.0
77.0
The function returns a number so its caller can choose how to display or reuse it.
Exercise 2 · Count qualifying sessions
Given [5, 20, 0, 15, 30], count sessions lasting at least 15 minutes. Use a loop and condition. The answer should be 3.
Show solution: count sessions
sessions = [5, 20, 0, 15, 30]
count = 0
for minutes in sessions:
if minutes >= 15:
count += 1
print(count)
Output
3
The increment is inside the condition, so short sessions do not increase the count.
Exercise 3 · Summarize a week
Write summarize_sessions(sessions) that returns a dictionary with total and average. For [15, 20, 10], expect 45 and 15.0. For an empty list, return 0 and 0.0 without dividing by zero.
Show solution: weekly summary
def summarize_sessions(sessions):
if not sessions:
return {"total": 0, "average": 0.0}
total = sum(sessions)
return {"total": total, "average": total / len(sessions)}
print(summarize_sessions([15, 20, 10]))
print(summarize_sessions([]))
Output
{'total': 45, 'average': 15.0}
{'total': 0, 'average': 0.0}
An empty list is false in a condition. Checking it first prevents division by zero; len() gives the number of items in a nonempty list.
9. Common questions and useful next steps
Why does changing indentation break my program?
Indentation defines which statements belong to a block. Keep four spaces per level and configure your editor to insert spaces consistently. Align elif and else with their if; indent the statements inside each branch. A missing colon or inconsistent indentation can stop the program before any code runs.
Should I learn decorators and async next?
First get comfortable writing functions, using collections, reading tracebacks, and checking a small project. Then follow a concrete need: add a file for saved history, split a larger program into modules, or write automated tests. Classes, decorators, and asynchronous code will be easier to understand when a project gives you a reason to use them.
Can I use random to generate passwords?
For passwords and other secrets, use the secrets module. The ordinary generators in random are intended for tasks such as simulations. Here is an optional standalone example producing a different 16-character password on each run:
import secrets
import string
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(16))
print(password)
secrets.choice() selects a character; the expression repeats that selection 16 times; join() combines the characters into a string. The output varies, so there is no fixed expected password. See the official secrets documentation.
Use readable names, keep functions focused, and apply consistent formatting. PEP 8 explains the conventions. When something fails, reproduce it with the smallest example you can, read the error, and check the relevant documentation before adding more code.
You now have a program with real input, reusable logic, and recoverable errors. A useful next step is to add calculation history: collect results in a list, then use the JSON example to save them. Write down the behavior you want before coding, and check both an empty history and several completed calculations.
Further reading