Python Hello World: Your First Program
Write your first Python program with print(), learn how Python runs code line by line and add comments. It all runs in your browser — no install.
print("Hello, World!")The essential Python syntax on one page. Every snippet comes from a lesson of our interactive Learn Python course — click "Practise" to write it yourself and get instant feedback.
Last updated on .
Write your first Python program with print(), learn how Python runs code line by line and add comments. It all runs in your browser — no install.
print("Hello, World!")Learn Python variables and the core data types — int, float, str, bool and None — plus type() and type conversion, with an interactive exercise.
hero = "Ada"
level = 3
print(hero, "is level", level) # Ada is level 3Master Python arithmetic: + - * /, floor division //, modulo %, exponent **, operator precedence and float gotchas. Practise with real code.
gold = 250 # int
price = 4.99 # float
huge = 2 ** 100 # ints can be as large as you like
budget = 1_000_000 # underscores make long numbers readableWork with Python strings: indexing, slicing, string methods like strip(), upper() and replace(), and formatting values with f-strings. Interactive lesson.
spell = "Fireball"
quote = 'Speak, friend, and enter.'
scroll = """Line one
Line two"""Make decisions in Python with if, elif and else, comparison and logical operators (and, or, not) and truthy values. Write and test real code.
health = 25
if health < 30:
print("Warning: low health!")
print("Turn over.")Repeat work with Python for loops, range(), while loops, break and continue. Learn the accumulator pattern and how to avoid infinite loops.
for letter in "hiss":
print(letter)Define your own Python functions with def, pass parameters, return values instead of printing them, and document them with docstrings and type hints.
def greet(name):
return f"Welcome to Serpent Hollow, {name}!"
message = greet("Ada")
print(message) # Welcome to Serpent Hollow, Ada!Learn Python default parameter values, keyword arguments, *args and **kwargs, keyword-only parameters and the mutable default argument trap.
def describe(name, job):
return f"{name} the {job}"
print(describe("Ada", "engineer")) # Ada the engineer
print(describe(job="wizard", name="Merl")) # Merl the wizardUnderstand Python variable scope (LEGB), global and nonlocal, closures and anonymous lambda functions — then pass functions around like any other value.
realm = "Serpent Hollow" # global
def welcome():
visitor = "Ada" # local
return f"{visitor} enters {realm}"
print(welcome()) # Ada enters Serpent Hollow
print(visitor) # NameError: name 'visitor' is not definedLearn Python lists: create them, read items by index, use negative indexes and slice with [start:stop:step] to copy, reverse and rotate sequences.
heroes = ["Ada", "Bo", "Cy"]
scores = [98, 75, 88]
mixed = ["potion", 3, True, None]
empty = []
print(len(heroes)) # 3
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list("hiss")) # ['h', 'i', 's', 's']Use Python list methods — append, extend, insert, remove, pop — and sort lists with sort() vs sorted(), reverse=True and key functions.
bag = ["rope"]
bag.append("torch") # add one item to the end
bag.extend(["map", "potion"]) # add every item from another iterable
bag.insert(0, "sword") # insert at a position
print(bag) # ['sword', 'rope', 'torch', 'map', 'potion']Learn Python tuples — immutable sequences for records and multiple return values — plus tuple unpacking, star unpacking and swapping variables.
point = (3, 4)
color = (255, 128, 0)
hero = ("Ada", 98)
single = (5,) # one-item tuple: the comma is required!
not_a_tuple = (5) # just the number 5 in parentheses
empty = ()Write Python list comprehensions to map, filter and flatten lists in one readable line — with if filters, conditional expressions and nested loops.
numbers = [1, 2, 3, 4]
doubled = []
for n in numbers:
doubled.append(n * 2)Learn Python dictionaries: create, read and update key-value pairs, use get(), items() and setdefault(), loop over dicts and count things.
hero = {"name": "Ada", "level": 3, "class": "wizard"}
prices = {"potion": 5, "rope": 2}
empty = {}
print(hero["name"]) # Ada
print(len(hero)) # 3
print(hero["mana"]) # KeyError: 'mana'Use Python sets to remove duplicates, test membership fast and combine data with union, intersection and difference. Interactive exercises.
elements = {"fire", "ice", "storm"}
rolls = set([3, 6, 3, 1, 6])
print(rolls) # {1, 3, 6}
print(set("hollow")) # {'h', 'o', 'l', 'w'} (order may vary)
empty = set() # NOT {} — that's an empty dict!Build Python dictionaries and sets in one line with dict and set comprehensions: transform, filter and invert data the Pythonic way.
squares = {n: n * n for n in range(1, 5)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16}
heroes = ["Ada", "Bo", "Cyrus"]
name_lengths = {name: len(name) for name in heroes}
print(name_lengths) # {'Ada': 3, 'Bo': 2, 'Cyrus': 5}Learn object-oriented Python: define classes, initialise objects with __init__ and self, write methods, and use instance vs class attributes.
class Potion:
def __init__(self, name, power):
self.name = name
self.power = power
healing = Potion("Healing", 25)
mana = Potion("Mana", 40)
print(healing.name, healing.power) # Healing 25
print(mana.power) # 40Reuse code with Python inheritance: create subclasses, override methods, extend parent classes with super() and check types with isinstance().
class Enemy:
def __init__(self, name, health):
self.name = name
self.health = health
def describe(self):
return f"{self.name} ({self.health} HP)"
def attack(self):
return 3
class Goblin(Enemy):
pass
grub = Goblin("Grub", 30)
print(grub.describe()) # Grub (30 HP)
print(grub.attack()) # 3Make Python classes feel built-in with dunder (magic) methods: __str__ and __repr__ for printing, __eq__ for equality and __add__ for operators.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
v = Vector(1, 2)
print(v) # <__main__.Vector object at 0x7f3a...>
print(Vector(1, 2) == Vector(1, 2)) # False — two different objectsCut boilerplate with Python dataclasses: auto-generated __init__, __repr__ and __eq__, default values, default_factory, frozen and ordered classes.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(3, 4)
print(p) # Point(x=3, y=4)
print(p.x) # 3
print(p == Point(3, 4)) # TrueHandle errors in Python with try, except, else and finally: catch specific exceptions, read error messages and clean up reliably.
age = int("twelve")Raise exceptions in Python with raise, design custom exception classes that carry extra data, re-raise errors and chain them with raise ... from.
def set_volume(level):
if not 0 <= level <= 10:
raise ValueError(f"Volume must be between 0 and 10, got {level}")
return level
set_volume(11) # ValueError: Volume must be between 0 and 10, got 11Understand Python iterators, iter() and next(), and write lazy generators with yield and generator expressions to process data efficiently.
letters = iter(["a", "b"])
print(next(letters)) # a
print(next(letters)) # b
print(next(letters, "done")) # done (a default instead of StopIteration)Write Pythonic loops with enumerate() and zip(), and sort anything with sorted(key=...), lambda functions and multi-key tuples. Interactive lesson.
heroes = ["Ada", "Bo", "Cy"]
for index, hero in enumerate(heroes):
print(index, hero) # 0 Ada / 1 Bo / 2 Cy
for rank, hero in enumerate(heroes, start=1):
print(f"{rank}. {hero}") # 1. Ada / 2. Bo / 3. Cy