Python reference
Each building block has a short explanation, an example with its exact output, and the mistakes people make most.
- print()Show values on the screen. Several values are separated by a space unless you change sep.
- input()Ask the user to type something. The answer always comes back as text.
- Variables and assignmentA variable is a name for a value. = stores a value, and the right side is worked out first.
- f-stringsPut variables and calculations inside text. Start the string with f and use curly brackets.
- len()Count the characters in a string or the items in a list, dictionary or other collection.
- range()A sequence of whole numbers for loops. It starts at 0 and stops before the end.
- if, elif and elseRun code only when a condition is true. Python runs the first branch that matches.
- for loopRepeat code for each item of a sequence, such as a list, a string or a range.
- while loopRepeat code as long as a condition is true. Use it when you do not know the number of turns.
- List methods: append and removeLists can change. append adds to the end, and remove takes out the first matching item.
- Dictionaries and dict.get()Look values up by key. get() returns a default instead of an error when the key is missing.
- def and returnDefine a function with def. return hands a value back to the caller.
- try and exceptHandle an error instead of crashing. Code in try runs; if it raises the named error, except runs.
- classA blueprint for objects that bundle data (attributes) and actions (methods).
- json.dumps() and json.loads()Turn data into JSON text to save or send it, and back into Python data.
- is versus ==is asks whether two names are the same object. == asks whether their values match. Use is None for a missing value.
- TuplesA tuple is an ordered group that cannot change. Use it for fixed records such as a coordinate pair.
- SetsA set keeps unique items and answers fast membership questions. {} is an empty dict; the empty set is set().
- **kwargsExtra named arguments are collected into a dictionary. Read them with .get(key, default).
- yieldyield turns a function into a generator: it hands out one value, pauses, and continues when asked again.
- super()Call the parent method from a subclass. Write the extra behaviour after (or around) that call.
- matchChoose a branch from one value. case _ is the default and must come last.
- re.searchFind the first match of a pattern. Use a raw string r"..." so backslashes stay backslashes. group(1) is the first pair of brackets.