Learn Python
Step by Step
A complete tutorial for absolute beginners. No previous experience needed, no jargon, just the fundamentals explained clearly with examples you can run yourself.
Python is one of the most beginner-friendly programming languages, and it has become the go-to choice for web development, data science, automation, machine learning, and much more. Whether you are completely new to coding or switching from another language, this tutorial walks you through the fundamentals with clear examples and explanations.
Everything below is broken into small, digestible parts so you can learn Python from scratch. You do not need to install anything to follow along at first, but running the examples yourself is the fastest way to learn.
What Is Python and Why Learn It?
Python is a high-level, interpreted programming language. "High-level" means it reads closer to English than to machine code, and "interpreted" means you can run your code directly without a separate compile step. That combination is a big part of why beginners pick it up so quickly.
Why Python is a great first language
- Simple, readable syntax that looks almost like plain English
- A huge community and library ecosystem, so help and ready-made tools are everywhere
- Versatility: web apps, AI, automation, data analysis, games, and more all use Python
Installing Python and Setting Up
Install Python
Go to python.org and download the latest stable version (Python 3.12 or newer). On the installer, tick "Add Python to PATH".
Choose an editor
An editor is where you write code. Any of the options below works well to start.
Check it works
Open a terminal and type python --version. If you see a version number, you are ready.
Editor options
- IDLE: comes bundled with Python, zero setup, perfect for your very first programs
- VS Code: lightweight, powerful, and the most popular choice for real work
- PyCharm: feature-rich and built specifically for Python
Writing Your First Python Program
Open your editor, create a file called hello.py, and type this single line:
print("Hello, world!")
Save the file and run it. You should see:
That is a complete Python program. The print() function displays whatever you put inside the parentheses. The text in quotes is called a string, which is just programming-speak for a piece of text.
Variables and Data Types
A variable is a name that stores a value so you can use it later. In Python you create one just by assigning a value with =. You never have to declare the type up front, Python figures it out for you.
name = "Alice" # String (text) age = 25 # Integer (whole number) height = 5.5 # Float (decimal number) is_student = True # Boolean (True or False)
The core built-in types
| Type | Example | Used for |
|---|---|---|
str | "hello" | Text of any length |
int | 42 | Whole numbers |
float | 3.14 | Numbers with decimals |
bool | True / False | Yes/no, on/off logic |
Operators in Python
Operators let you work with values. There are three groups you will use constantly.
Arithmetic, comparison, and logical
| Group | Operators |
|---|---|
| Arithmetic | + - * / // % ** |
| Comparison | == != < > <= >= |
| Logical | and or not |
x = 10 y = 3 print(x + y) # 13 addition print(x / y) # 3.333... true division print(x // y) # 3 floor division (drops the remainder) print(x % y) # 1 modulo (the remainder) print(x ** y) # 1000 exponent (10 to the power 3)
/ always gives a decimal, while // rounds down to a whole number. The % operator (modulo) is surprisingly useful, for example n % 2 == 0 checks if a number is even.
Control Flow: if, elif, else
Control flow lets your program make decisions. An if statement runs a block of code only when a condition is true.
num = 7 if num > 0: print("Positive") elif num == 0: print("Zero") else: print("Negative")
if belongs to it. Be consistent: four spaces per level is the standard.
Loops: for and while
Loops repeat a block of code. Use a for loop when you know how many times to repeat or want to go through a collection, and a while loop when you want to repeat until a condition changes.
The for loop
for i in range(5): print(i)
range(5) produces the numbers 0 up to (but not including) 5. This off-by-one detail trips up almost every beginner, so keep it in mind.
The while loop
count = 0 while count < 3: print(count) count += 1 # same as: count = count + 1
while loop keeps going as long as its condition is true. If you forget to change the variable inside the loop (here, count += 1), it will run forever. Always make sure the condition will eventually become false.
Functions in Python
A function is a reusable block of code you can call by name. Functions keep your programs organised and save you from repeating yourself.
def greet(name): print("Hello, " + name) greet("Alice") # Hello, Alice
Functions can also return a value, which you can store or use elsewhere:
def add(a, b): return a + b result = add(3, 4) print(result) # 7
print() shows a value on screen; return hands a value back to your code so you can keep working with it. Beginners often confuse the two. If you need to use the result later, you want return.
Lists, Tuples, and Dictionaries
These are Python's everyday containers for holding multiple values. Choosing the right one is a real skill, so here is when to reach for each.
Lists: ordered and changeable
fruits = ["apple", "banana", "cherry"] print(fruits[0]) # apple (indexing starts at 0) fruits.append("mango") # add an item to the end
Tuples: ordered but fixed
colors = ("red", "green", "blue") # colors[0] = "yellow" would cause an error, tuples can't change
Use a tuple when the collection should never change, like coordinates or RGB colour values. The fact that it cannot change is a feature, not a limitation.
Dictionaries: key-value pairs
person = {"name": "Alice", "age": 25} print(person["name"]) # Alice person["city"] = "London" # add a new key
| Container | Ordered? | Changeable? | Best for |
|---|---|---|---|
| List | Yes | Yes | A collection you will add to or edit |
| Tuple | Yes | No | Fixed data that should not change |
| Dictionary | Yes | Yes | Looking things up by a name or key |
Error Handling with try and except
Programs sometimes hit problems: a file is missing, a user types text where a number was expected, or you accidentally divide by zero. Error handling lets your program respond gracefully instead of crashing.
try: x = 5 / 0 except ZeroDivisionError: print("You can't divide by zero!") finally: print("Execution complete.")
The try block holds code that might fail. If it does, the matching except block runs instead of the program crashing. The optional finally block always runs, whether or not an error happened, which makes it useful for cleanup.
File Handling
Reading and writing files lets your programs save data and load it back later. The with statement is the recommended way because it closes the file for you automatically, even if something goes wrong.
with open("example.txt", "w") as f: f.write("Hello from Python!")
with open("example.txt", "r") as f: content = f.read() print(content) # Hello from Python!
The second argument is the mode: "w" writes (and overwrites), "r" reads, and "a" appends to the end of an existing file.
Introduction to OOP
Object-Oriented Programming (OOP) is a way of structuring code around objects that bundle data and behaviour together. It is how larger Python programs stay organised.
class Person: def __init__(self, name): self.name = name def greet(self): print("Hello, my name is", self.name) p = Person("Alice") p.greet() # Hello, my name is Alice
The key ideas
- Class: a blueprint that describes what an object looks like and can do
- Object: an actual thing created from that blueprint (here,
p) - __init__: the constructor, which runs automatically when you create an object
- self: refers to the specific object, so each one keeps its own data
- Method: a function that belongs to a class (like
greet)
What to Learn Next
Once you are comfortable with the basics, these standard library modules and third-party packages are the natural next things to explore:
Tips for learning Python well
- Practice regularly by building small projects, not just reading
- Read other people's code: GitHub is a great place to start
- Visualise how code runs with a tool like Python Tutor when something confuses you
- Work through coding challenges to cement what you have learned
