Python is a readable, general-purpose programming language used for automation, web development, data analysis and artificial intelligence. This guide takes you from nothing to a small working program: why Python is worth learning, how to install it, and the core building blocks you’ll use in every script, with examples you can copy and run.
Why learn Python?
- Beginner-friendly: the syntax is short and reads almost like English, so you spend your effort on the problem rather than on punctuation.
- Versatile: the same language runs web back ends, automation scripts, data analysis, machine learning and test suites.
- Well supported: a large community, thorough official documentation and mature libraries mean help is easy to find.
- Transferable habits: breaking problems into steps, testing ideas and reading error messages carry over to any language you learn later.
Install Python and check it works
Download the current version from the official Python downloads page. On Windows, tick the option to add Python to your PATH during installation so you can run it from the command line. On macOS and Linux, use the installer or your package manager.
Open a terminal and check the version:
python --version
On many systems the command is python3 instead, and on Windows you can also use py. If one isn’t recognised, try the others.
Write and run your first program
Create a file called hello.py containing one line:
print("Hello, world!")
Save it, then run it from the same folder:
python hello.py
The terminal prints Hello, world!. That loop of writing code, running it, reading the result and adjusting is how programming becomes familiar, so get used to running your files often.
Variables and data types
A variable is a name that points to a value. You don’t declare a type; Python works it out from the value you assign. These are the types you’ll use most:
age = 25 # int: whole number
price = 12.50 # float: decimal number
name = "Asha" # str: text
is_member = True # bool: True or False
scores = [72, 88, 95] # list: ordered, changeable collection
person = {"name": "Asha", "age": 25} # dict: key-value pairs
print(f"{name} is {age} and paid £{price:.2f}")
scores.append(60)
print(scores, person["name"])
Output:
Asha is 25 and paid £12.50 [72, 88, 95, 60] Asha
The f"..." string is an f-string: anything inside curly braces is replaced with its value, and :.2f formats a number to two decimal places. Use type(value) whenever you’re unsure what type something is.
Conditions and loops
Control flow decides which lines run and how often. Python uses indentation (four spaces by convention) to mark which lines belong to an if, a loop or a function, so consistent indentation isn’t just style: it changes what the program does.
scores = [72, 88, 95, 60]
# for: repeat once for each item in a collection
for score in scores:
if score >= 90:
print(score, "distinction")
elif score >= 70:
print(score, "pass")
else:
print(score, "resit")
# while: repeat as long as a condition is true
count = 3
while count > 0:
print(count)
count -= 1
print("Lift off!")
# range: loop over a sequence of numbers (the end is excluded)
for i in range(1, 4):
print(i, end=" ")
Output:
72 pass 88 pass 95 distinction 60 resit 3 2 1 Lift off! 1 2 3
Prefer for when you know what you’re looping over, and while when you’re waiting for something to change. A while loop whose condition never becomes false runs forever; press Ctrl+C to stop it.
Functions
A function groups steps under a name so you can reuse them. Define it with def, and use return to hand a result back to the caller instead of just printing it, so the result can be used elsewhere.
def average(numbers):
"""Return the mean of a list of numbers."""
return sum(numbers) / len(numbers)
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(average([72, 88, 95, 60]))
print(greet("Asha"))
print(greet("Ben", greeting="Good morning"))
Output:
78.75 Hello, Asha! Good morning, Ben!
The text in triple quotes is a docstring: a short description that editors and help(average) will show. greeting="Hello" is a default value, used when the caller doesn’t pass one.
Reading and writing files
Open files with a with block. It closes the file for you when the block ends, even if an error happens part-way through, which is safer than calling close() yourself. Passing encoding="utf-8" avoids surprises with accented characters or symbols such as £ on different operating systems.
# "w" creates the file, or replaces it if it exists
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("First line\n")
file.write("Second line\n")
# with no mode given, the file is opened for reading
with open("notes.txt", encoding="utf-8") as file:
for line in file:
print(line.strip())
This prints the two lines back. Use mode "a" to add to the end of a file instead of replacing it.
Modules, the standard library and packages
Python ships with a large standard library of modules for maths, dates, files, text, testing and much more. Bring one into your program with import:
import math
from datetime import date
print(math.sqrt(25)) # 5.0
print(date(2026, 1, 1).strftime("%A")) # Thursday
For anything beyond the standard library, install third-party packages with pip. Do it inside a virtual environment, a private folder of packages for one project, so different projects can’t break each other:
python -m venv .venv source .venv/bin/activate # on Windows: .venv\Scripts\activate pip install requests
How to read an error message
Errors are feedback, not failure. When something goes wrong, Python prints a traceback. Read it from the bottom up:
Traceback (most recent call last):
File "err.py", line 2, in <module>
print(scores[2])
~~~~~~^^^
IndexError: list index out of range
The last line names the problem (IndexError: asking for an item that doesn’t exist; scores had only two items, and positions start at 0). The lines above it show the file and line number. Search for the exact message if it’s unfamiliar, and change one thing at a time when you fix it.
Put it together: a word counter
Here’s a small, complete program that uses most of the ideas above: a function, a file, a loop, a list and a module from the standard library. It finds the most common words in a text file.
from collections import Counter
from pathlib import Path
def count_words(path, top=5):
"""Return the most common words in a text file."""
text = Path(path).read_text(encoding="utf-8").lower()
words = [word.strip(".,!?;:\"'()") for word in text.split()]
words = [word for word in words if word]
return Counter(words).most_common(top)
if __name__ == "__main__":
for word, count in count_words("sample.txt", top=3):
print(f"{word}: {count}")
With a sample.txt containing “The cat sat on the mat. The dog sat too! The end.”, it prints:
the: 4 sat: 2 cat: 1
The lines in square brackets are list comprehensions, a compact way to build a new list from an existing one. The if __name__ == "__main__": check means the loop runs only when you run the file directly, so you could import count_words into another program without it printing anything. Try extending it: ignore common words such as “the”, or count words across every file in a folder.
A learning routine that works
- Practise little and often. Twenty minutes a day beats one long session a week.
- Type the examples yourself rather than pasting them, then change something and predict what will happen before you run it.
- Build tiny projects as soon as you can: a number-guessing game, a script that renames files, or a simple expense tracker.
- When you’re stuck, read the error, check the documentation, and only then search for a solution, making sure you understand it before using it.
Further reading
- The official Python tutorial, a structured introduction from the people who make Python
- The Python standard library reference, for discovering the built-in modules
- venv: creating virtual environments
