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
- and, or, not (logical operators)and, or and not combine and flip conditions: and needs both sides true, or needs one, and not turns True into False.
- assert statementassert checks a condition that should always be true and stops with an AssertionError when it is not. Ideal for tests and sanity checks.
- break statementbreak stops a for or while loop immediately and jumps to the first line after it, skipping the rest of the rounds.
- class statementclass defines a new type of object that bundles data (attributes) and the functions that work on it (methods) under one name.
- continue statementcontinue skips the rest of the current loop round and jumps straight to the next one, without ending the loop.
- 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.
- del statementdel removes a name, a list item, a slice of a list or a dictionary key. It deletes the reference, not necessarily the object itself.
- dict comprehensionA dict comprehension builds a new dictionary in one line from any collection, choosing each key and value, with an optional filter.
- 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.
- global and nonlocalglobal lets a function change a variable defined at the top of the file; nonlocal lets an inner function change one from the outer function.
- 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.
- in operator (membership)The in operator checks whether a value is inside a list, string, dictionary or set, and gives True or False. not in checks the opposite.
- is operator (identity vs ==)is checks whether two names point to the very same object, while == checks whether two values are equal. Use is mainly with None.
- 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.
- match / casematch compares one value against a list of case patterns and runs the first that fits. It needs Python 3.10 or newer.
- pass statementpass is a placeholder that does nothing. Use it where Python needs a statement but you have no code to write yet.
- raise statementraise stops normal execution by throwing an exception, so bad input or impossible situations are reported instead of ignored.
- 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.
- with statementwith sets something up, runs your block, then always cleans up, even after an error. It is the standard way to open files.
- yield (generators)yield turns a function into a generator that hands out values one at a time, pausing between them, instead of building a whole list.