This page is the short version of Python. Variables, the handful of types you will use daily, if statements, loops, functions and lists — enough to read most beginner code and write your own small programs. Every section has an example you can paste into a file and run, and a note about the mistake that catches people out.
Running your first program#
Save this as hello.py and run python hello.py in a terminal from the same folder:
name = "Ana"
print("Hello, " + name)
Hello, Ana
That is a complete Python program. No boilerplate, no main function required, no compilation step. This is a large part of why Python is recommended as a first language.
Variables#
A variable is a name pointing at a value. You do not declare a type — Python works it out.
age = 34 # int, a whole number
price = 12.99 # float, a decimal number
name = "Ana" # str, text
is_member = True # bool, True or False
nothing = None # NoneType, "no value"
print(type(age)) # <class 'int'>
print(type(price)) # <class 'float'>
Names can be reassigned freely, including to a different type:
count = 5
count = "five" # legal, though usually a sign of confused code
Text and numbers do not mix automatically#
age = 34
print("I am " + age)
TypeError: can only concatenate str (not "int") to str
Convert explicitly, or use an f-string, which is almost always the better choice:
print("I am " + str(age))
print(f"I am {age}") # f-string - preferred
print(f"Next year: {age + 1}") # any expression works inside the braces
Getting input#
answer = input("How old are you? ")
print(type(answer)) # <class 'str'> - always a string
age = int(answer) # convert if you need to do maths
print(f"In ten years you will be {age + 10}")
Making decisions#
score = 72
if score >= 80:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(grade) # B
The indentation is not decoration. Python uses it to decide which lines belong to the if. Four spaces is the convention; whatever you choose, be consistent, and never mix tabs and spaces in the same file.
The comparison operators are == (equal), != (not equal), <, >, <= and >=. Combine conditions with and, or and not:
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("Come in")
if not has_ticket:
print("Buy a ticket first")
Loops#
Use for when you know what you are looping over, and while when you are waiting for a condition to change.
for fruit in ["apple", "pear", "plum"]:
print(fruit)
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
total = 0
while total < 100:
total = total + 15
print(total) # 105
Two keywords change the flow inside a loop:
for n in range(10):
if n == 3:
continue # skip the rest of this iteration
if n == 6:
break # leave the loop entirely
print(n) # 0 1 2 4 5
Lists#
scores = [88, 72, 95, 61]
print(scores[0]) # 88 - counting starts at zero
print(scores[-1]) # 61 - last item
print(len(scores)) # 4
print(scores[1:3]) # [72, 95] - up to but not including index 3
scores.append(70) # add to the end
scores.sort() # sort in place
print(max(scores), min(scores), sum(scores))
Building a new list from an old one is common enough that Python has a short form for it:
doubled = [s * 2 for s in scores]
passing = [s for s in scores if s >= 70]
Dictionaries#
A dictionary stores pairs — a key you look things up by, and a value.
person = {"name": "Ana", "age": 34, "city": "Leeds"}
print(person["name"]) # Ana
print(person.get("email")) # None - no error
print(person.get("email", "not set"))
person["email"] = "ana@example.com" # add or update
for key, value in person.items():
print(key, "->", value)
if "age" in person:
print("age is set")
Square-bracket access on a missing key raises KeyError. The .get() method returns None instead. Use whichever matches what should happen when the key is genuinely absent.
Functions#
def average(numbers):
if not numbers:
return 0
return sum(numbers) / len(numbers)
print(average([88, 72, 95])) # 85.0
print(average([])) # 0
Functions can have default values and be called with named arguments:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ana"))
print(greet("Ana", "Good morning"))
print(greet(greeting="Hi", name="Sam"))
Comments#
# A comment explains why, not what.
tax = price * 0.2 # standard rate at the time of writing
def area(width, height):
"""Return the area of a rectangle."""
return width * height
The triple-quoted string just under a def is a docstring. It shows up when someone calls help(area), so it is worth writing for anything non-obvious.
Questions people ask#
Which Python version should I install?
The latest stable Python 3 release. Python 2 reached end of life in 2020 — if a tutorial uses print "hello" without brackets, it is written for Python 2 and you should find a newer one.
Do I need an IDE to start?
No, but it helps. A plain text editor and a terminal are enough. VS Code with the Python extension is the common free choice and gives you error highlighting as you type, which shortens the feedback loop considerably.
Why does my code fail with IndentationError?
Either a line that should be indented is not, or your editor is mixing tabs and spaces. Set your editor to insert spaces when you press Tab and the problem disappears for good.
How long does it take to get comfortable with this?
Reading this page takes twenty minutes. Being able to write it from memory takes a few weeks of regular practice. The gap between those two is entirely made of typing code yourself rather than reading it.
Where to go next#
- Python for loops explained — the loop you will use most, in more depth.
- Python functions explained — arguments, scope and return values properly.
- Why is my Python code not working? — for the first errors you will hit.