Python · Beginner Tutorial

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.

Beginner friendly 13 sections ~30 min read

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.

01

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
Who uses Python?
Companies like Google, Netflix, NASA, and Instagram rely on Python every day. Learning it opens doors across almost every area of software.

02

Installing Python and Setting Up

Step 1

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".

Step 2

Choose an editor

An editor is where you write code. Any of the options below works well to start.

Step 3

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
Tip
You do not need a perfect setup to start learning. If installing feels like a hurdle, try an online editor like replit.com or the official Python shell first, then install properly once you are hooked.

03

Writing Your First Python Program

Open your editor, create a file called hello.py, and type this single line:

hello.py
print("Hello, world!")

Save the file and run it. You should see:

OutputHello, world!

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.


04

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

TypeExampleUsed for
str"hello"Text of any length
int42Whole numbers
float3.14Numbers with decimals
boolTrue / FalseYes/no, on/off logic
Dynamically typed
Because Python is dynamically typed, the same variable can hold a number now and a string later. Convenient, but it means you should give variables clear names so their purpose is obvious.

05

Operators in Python

Operators let you work with values. There are three groups you will use constantly.

Arithmetic, comparison, and logical

GroupOperators
Arithmetic+ - * / // % **
Comparison== != < > <= >=
Logicaland 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)
Worth remembering
/ 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.

06

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")
OutputPositive
Indentation matters
Python uses indentation (the spaces at the start of a line) to group code, instead of curly braces. Everything indented under the if belongs to it. Be consistent: four spaces per level is the standard.

07

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)
Output0 1 2 3 4

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
Avoid infinite loops
A 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.

08

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 vs return
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.

09

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
ContainerOrdered?Changeable?Best for
ListYesYesA collection you will add to or edit
TupleYesNoFixed data that should not change
DictionaryYesYesLooking things up by a name or key

10

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.")
OutputYou can't divide by zero! 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.


11

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.

writing
with open("example.txt", "w") as f:
    f.write("Hello from Python!")
reading
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.

Go deeper
File handling is a big topic once you start working with CSV and JSON data. When you are ready, the full File Handling in Python guide covers it all.

12

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)
Go deeper
OOP has four core pillars: encapsulation, inheritance, polymorphism, and abstraction. The full OOP in Python guide explains each one with examples.

13

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:

math, random: calculations and randomness
datetime: dates and times
os, sys: system-level tasks
requests: fetching data from the web
numpy, pandas, matplotlib: data science
tkinter, pygame: GUIs and games

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
Where this fits
This tutorial covers the foundations. From here you can branch into web development with Flask or Django, data analysis, machine learning, or automation scripts that save you time every day.
Ready for the full picture?
This tutorial is your first step. The complete Python roadmap shows you every stage from here to building and deploying real applications, in order, so you always know what to learn next.
View the Python roadmap
Scroll to Top