Print text to the screen: print('Hello') Get input from the user: input('Name? ') Make a variable: x = 5 Comment a line: # this is a comment Integer division: 7 // 2 gives 3 Remainder (modulo): 7 % 2 gives 1 Exponent (power): 2 ** 3 gives 8 Not equal comparison: x != y Equal comparison: x == y Logical and: a and b Logical or: a or b Logical not: not a If statement: if x > 3: Else if: elif x == 3: Else: else: For loop over a range of 5: for i in range(5): Range from 1 to 10: range(1, 11) While loop: while x < 10: Stop a loop early: break Skip to the next loop pass: continue Do nothing placeholder: pass Define a function: def greet(name): Return a value: return x Default parameter: def f(x=10): Lambda (small anonymous function): lambda x: x * 2 Make a list: nums = [1, 2, 3] Add to the end of a list: nums.append(4) Remove last item of a list: nums.pop() Length of a list or string: len(nums) First item of a list: nums[0] Last item of a list: nums[-1] Slice the first two items: nums[:2] Sort a list in place: nums.sort() Sorted copy of a list: sorted(nums) Reverse a list: nums.reverse() or nums[::-1] Tuple (unchangeable sequence): t = (1, 2, 3) Set (unique items): s = {1, 2, 3} Dictionary: d = {'a': 1, 'b': 2} Get a dictionary value: d['a'] Loop over dictionary items: for k, v in d.items(): Check if item is in a list: 3 in nums Convert to integer: int('5') Convert to string: str(5) Convert to float: float('3.5') Convert to list: list('abc') Type of a value: type(x) Join strings in a list: ', '.join(words) Split a string into a list: 'a b c'.split() Uppercase a string: 'hi'.upper() Replace text in a string: s.replace('a', 'b') Strip whitespace: s.strip() F-string: f'Hello {name}' Multi-line string: '''text over lines''' Import a module: import math Import one name: from math import sqrt Random integer: import random; random.randint(1, 6) Square root: math.sqrt(16) Absolute value: abs(-3) Round a number: round(3.6) Maximum of values: max(1, 5, 3) Sum of a list: sum(nums) List comprehension: [x * 2 for x in nums] Open and read a file: with open('f.txt') as f: data = f.read() Handle errors: try: ... except ValueError: ... Raise an error: raise ValueError('bad') Define a class: class Dog: Constructor method: def __init__(self, name): The current object inside a method: self None value: None Boolean values: True and False Enumerate with index: for i, x in enumerate(nums): Zip two lists: zip(a, b) Check if a value is None: x is None Run code only when file is the main program: if __name__ == '__main__': Python's creator: Guido van Rossum, who released Python in 1991 Free flashcards from Peabody at peabody.kids/flashcards/tech-python-syntax