Python reference

Python statements and syntax

The building blocks of every program: if, for, while, def, try, with, comprehensions and f-strings.

Statements and keywords are the grammar of Python: making decisions (if), repeating (for, while), defining functions (def, lambda) and classes, handling errors (try), and compact ways to build lists and text (comprehensions, f-strings, slicing).

Most used

class statementclass defines a new type of object that bundles data (attributes) and the functions that work on it (methods) under one name.def (functions)def creates a function: a named block of code you can run again and again with different inputs, and that can return a result.f-stringsAn f-string puts variables and expressions straight into text with {curly braces}, and can format numbers, dates and widths.for loopA for loop runs the same block of code once for every item in a list, string, range or any other collection.if statementAn if statement runs a block of code only when a condition is true, with elif and else for the other cases.import statementimport loads a module so you can use its functions, such as math.sqrt() or random.choice(), from the standard library or your own files.lambdalambda makes a small, nameless function in one expression. It is most useful as a key for sorted(), min(), max() and similar.list comprehensionA list comprehension builds a new list from another collection in one readable line, with an optional filter to keep only some items.return statementreturn ends a function and sends a value back to the code that called it. Without a value, or without return, you get None.slicing [start:stop:step]Slicing takes a part of a list, string or tuple with [start:stop:step]: the start is included, the stop is not, and step skips items.try / except / else / finallytry runs code that might fail; except catches the error so your program can react, and else and finally add extra steps.while loopA while loop repeats a block of code as long as its condition stays true, for when you do not know how many rounds you need.

All 26 statements and syntax

Spotted a mistake on this page? Tell us