Coding · Programming languages
Python tutorial for beginners
Short answer
Python is a general-purpose, interpreted language known for readable syntax that uses indentation instead of braces. Install Python 3, save print("Hello, world") in hello.py and run python3 hello.py. The core ideas are dynamic types, functions defined with def, built-in lists, dicts and sets, exceptions handled with try/except, and a large standard library.
What Python is and what it is used for
Python is a high-level, dynamically typed language first released by Guido van Rossum in 1991. Code is run by an interpreter (the reference one is CPython), so there is no separate compile step. It is used for data analysis and machine learning (NumPy, pandas, PyTorch), web back ends (Django, Flask, FastAPI), automation scripts, scientific computing and teaching. Python 2 reached end of life in 2020, so always learn Python 3.
Install Python and run Hello, world
Download an installer from python.org (Windows, macOS) or use your package manager on Linux. Check the install with python3 --version (on Windows the command is often py or python). Save this file as hello.py:
print("Hello, world")python3 hello.py
# Hello, worldRunning python3 with no file opens the interactive prompt (REPL), which is useful for trying one line at a time.
Variables and basic types
A variable is created by assigning to it. You do not declare a type; the value carries its type, and type(x) tells you what it is.
| Type | Example | Notes |
|---|---|---|
int | 42, -7, 10**20 | Whole numbers of any size |
float | 3.14, 1e-3 | 64-bit floating point |
bool | True, False | Capitalized |
str | "hi", 'hi' | Immutable Unicode text |
None | None | The absence of a value |
name = "Ada"
age = 36
height = 1.65
print(f"{name} is {age} years old") # Ada is 36 years old
print(7 / 2, 7 // 2, 7 % 2) # 3.5 3 1
print(int("12") + 1) # 13Control flow: if, for and while
Blocks start with a colon and are defined by indentation (4 spaces by convention). for loops iterate over any sequence; range(n) gives the numbers 0 to n−1.
score = 72
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
else:
grade = "C"
print(grade) # B
for i in range(3):
print(i) # 0, then 1, then 2
n = 10
while n > 1:
n = n // 2
print(n) # 1Functions
Define functions with def. Parameters can have default values, and callers can pass arguments by name. A function without return returns None.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Lin")) # Hello, Lin!
print(greet("Lin", greeting="Hi")) # Hi, Lin!
square = lambda x: x * x
print(square(5)) # 25Type hints such as def area(w: float, h: float) -> float: document intent and let tools like mypy check your code, but the interpreter does not enforce them.
Lists, tuples, dicts and sets
| Type | Literal | Ordered | Mutable | Typical use |
|---|---|---|---|---|
list | [1, 2, 3] | Yes | Yes | A sequence you change |
tuple | (1, 2) | Yes | No | A fixed group of values |
dict | {"a": 1} | Insertion order | Yes | Key to value lookup |
set | {1, 2} | No | Yes | Unique items, membership tests |
nums = [3, 1, 2]
nums.append(5)
nums.sort()
print(nums, nums[0], nums[-1], nums[1:3]) # [1, 2, 3, 5] 1 5 [2, 3]
ages = {"ann": 31, "bob": 25}
ages["cy"] = 40
for person, age in ages.items():
print(person, age)
print(ages.get("zed", 0)) # 0
squares = [x * x for x in range(5) if x % 2 == 0]
print(squares) # [0, 4, 16]The last line is a list comprehension, one of Python's signature features: it builds a list from a loop and an optional filter in one expression. Dict and set comprehensions work the same way.
Signature features: unpacking, with and generators
a, b = 1, 2
a, b = b, a # swap without a temporary
first, *rest = [1, 2, 3, 4]
print(first, rest) # 1 [2, 3, 4]
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("line one\n") # file is closed automatically
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(3))) # [3, 2, 1]The with statement runs setup and cleanup code for you (here, closing the file even if an error happens). A function that uses yield is a generator: it produces values lazily, one at a time, which saves memory on large data.
Error handling with try and except
Errors are raised as exceptions. Catch the specific exception types you expect, and use finally for code that must always run.
def parse_age(text):
try:
age = int(text)
except ValueError:
print(f"not a number: {text!r}")
return None
if age < 0:
raise ValueError("age cannot be negative")
return age
print(parse_age("41")) # 41
print(parse_age("abc")) # not a number: 'abc', then NoneA small complete program: word counter
This script reads a text file given on the command line and prints the five most common words. It uses the standard library only.
import sys
from collections import Counter
def top_words(path, n=5):
with open(path, encoding="utf-8") as f:
words = f.read().lower().split()
cleaned = [w.strip(".,;:!?\"'()") for w in words]
return Counter(w for w in cleaned if w).most_common(n)
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("usage: python3 count.py FILE")
try:
for word, count in top_words(sys.argv[1]):
print(f"{count:5} {word}")
except FileNotFoundError:
sys.exit(f"file not found: {sys.argv[1]}")Run it with python3 count.py notes.txt. The if __name__ == "__main__": check lets the file be imported as a module without running the script part.
Common beginner mistakes
- Mixing tabs and spaces, or inconsistent indentation, causes
IndentationError. Configure your editor to insert 4 spaces. =assigns and==compares. Useisonly forNone(if x is None).input()always returns a string; convert withint()orfloat()before doing math.- Copying a list with
b = adoes not copy it; both names point to the same list. Useb = a.copy()orb = list(a). - Install packages inside a virtual environment (
python3 -m venv .venv) instead of into the system Python.
Where to go next
Work through the official Python Tutorial, then browse the Library Reference to learn modules such as pathlib, json, datetime and itertools. Learn pip and virtual environments for third-party packages, and write tests with unittest or pytest. After that, pick a direction: web (Django or FastAPI), data (pandas), or automation.
FAQ
Is Python good for beginners?
Yes. Its syntax is short and close to plain English, errors are reported clearly, and you can try code line by line in the REPL. It is also widely used in industry, so beginner skills stay useful.
Is Python compiled or interpreted?
CPython compiles source code to bytecode and then interprets that bytecode, all automatically when you run a script. You never run a separate compile step.
What is the difference between a list and a tuple?
A list is mutable: you can add, remove and change items. A tuple is immutable, so it is used for fixed groups of values and can be a dict key.
Why is my Python code slow?
Pure Python loops are slower than compiled languages. Use built-in functions, comprehensions and libraries such as NumPy, which run their inner loops in C.
Should I use python or python3 on the command line?
On macOS and most Linux systems use python3, because python may be missing or point to something else. On Windows the py launcher is the usual choice.