Python Cheat Sheet

Python is one of the most popular programming languages. It currently takes first place both in the Tiobe index and the PYPL index and has been named Language of the Year in 2007, 2010, 2018, 2020, and 2021. This popularity stems both from Python’s versatility and ease of use. Python can be used for Web and Internet Development, Data Analysis and Machine Learning, Scripting, Software Testing, and Desktop GUIs (graphical user interfaces). Python uses a simple syntax and is very beginner-friendly. It is therefore a great choice for entry-level coders. The Python cheat sheet will introduce you to some important Python concepts.

Python Syntax

Python uses an elegant syntax and uncluttered layout. Combined with frequently used English keywords like ‘continue’, ‘return’, and ‘import’, this makes Python a highly readable language.

Indentation

One of the main characteristics of Python is indentation. While other programming languages, like Java and JavaScript, use braces to separate blocks of code, Python code blocks are identified by different levels of line indentation. Here is a code example using multiple levels of indentation:

def printer_errors(s):
    errors = 0 # first level of indentation
    for letter in s:
        if letter > 'm': # second level of indentation
            errors += 1 # third level of indentation
    return f'{errors}/{len(s)}' # first level of indentation

Writing the code without or with wrong indentation will lead to an error, and the code won’t be executed. It is best practice to use 4 spaces per level of indentation. It is possible to use either spaces or the Tabulator key for indentation, but you should stick to using either spaces or tabs. 

Comments

The hash sign from the above example is used for comments. Everything after the hash sign will be ignored by the Python interpreter and is used to add comments either for yourself or other people reading the code. Comments can be added above a line of code or next to a line of code, like in the above example. For long comments that span multiple lines, the hash sign can be added to the start of each new line, or the comment can be placed inside triple-quotes, like in the instruction below:

# The function returns the number of errors in a given control string.
# Letters from a to m are used to differentiate between colours.
# All other letters indicate an error.
# Write a function that returns the number of errors and the length of the control string.

'''
Examples:
s = 'adgbfbchaifjm'
printer_errors(s) # Output: '0/14'
'''

Quotation

It is possible to use single (‘), double (“), and triple (”’ or “””) quotes in Python. It is, however, important and necessary to use the same kind of quote at the start and end of a string. If the string itself contains quotes, they must not match the outer quotes. Like with comments, triple quotes are used for strings that span multiple lines. See the examples below:

name = 'Thomas'
colour = "blue"
sentence = "It's a pleasure to meet you!" # note the single quote 
paragraph = '''One Ring to rule them all, One Ring to find them, One Ring to bring them all, and in the darkness bind them.'''

Keywords

A Python identifier is a name used to identify a variable, function, class or module. It is best practice to use descriptive names, like ‘first_name’ or ‘calculate_stardate(year)’, to make the code easier to understand. Some identifiers are reserved by the Python language and cannot be used as ordinary identifiers. They are listed in the table below.

Falseawaitelseimportpass
Nonebreakexceptinraise
Trueclassfinallyisreturn
andcontinueforlambdatry
asdeffromnonlocalwhile
assertdelglobalnotwith
asyncelififoryield

Python primitive data structures

There are four types of primitive data structures in Python. They contain pure values of data and are essential for data manipulation. 

String

To display sequences of character data in Python, the string type (abbreviated as str) is used. In most cases, strings will be words, but it is possible to put licence plates, passwords, symbols, or even numbers into an str variable.  A string can be empty. The only limitation regarding length is the available computer memory. Strings can be used with single, double, and triple quotes like mentioned above in the Quotation section.

String methods

Strings in Python are immutable, which means they cannot be changed. However, it is possible to return a modified copy of a string by using string methods. To keep the modified string, it must be assigned to a new variable! Below, the most common string methods are listed with a short explanation.

text = 'Hello, World!' # assign 'Hello, World!' to the variable text
vulcan_greeting = ' Live long and prosper! ' # note the spaces at the start and end of the string
list_of_strings = ['Nice', 'to', 'meet', 'you']

' '.join(list_of_strings) # join all the strings by the delimiter (in this case an empty space). Output: 'Nice to meet you'
text.capitalize() # convert the first character to upper case. Output: 'Hello, world!'
text.count('o') # return the number of occurrences of the specified substring. Output: 2
text.endswith('o') # return True if the string ends with the specified substring. Output: False
text.find('o') # return the lowest index of the specified substring. Output: 4 (the index starts with 0)
text.islower() # return True if all cased characters are lowercase and the string contains at least one character. Output: False
text.istitle() # return True if the string is titlecased and contains at least one character. Output: True
text.isupper() # return True if the string is in uppercase and contains at least one character. Output: False
vulcan_greeting.lstrip() # remove the left whitespace. Output: 'Live long and prosper!'
text.lower() # convert the string into lower case. Output: 'hello, world!'
text.replace('World', 'Universe') # return the string with all occurrences of the first substring replaced by the second substring. Output: 'Hello, Universe'
vulcan_greeting.rsplit() # remove the right whitespace. Output ' Live long and prosper!'
text.split() # split the string into separate words and return a list. Output: ['Hello,', 'World']
vulcan_greeting.strip() # remove whitespace from both ends of the string. Output: 'Live long and prosper!'
text.startswith('o') # return True if the string starts with the specified substring. Output: False
text.swapcase() # swaps lower case to upper case and vice versa. Output: 'hELLO, wORLD'
vulcan_greeting.title() # convert the first letter of each word to upper case. Output: 'Live Long And Prosper!'
text.upper() # convert the string into upper case. Output: 'HELLO, WORLD!'

String concatenation

It is possible to combine (or concatenate) multiple strings by using the + operator. When alpha-numeric strings are concatenated, the result might at first be surprising. Instead of adding them up, they are just written next to each other:

greeting = 'Hello!'
question = 'Do you want some coffee?'
greeting + question # Output:'Hello! Do you want some coffee?'
x = '7'
y = '5'
x + y # Output: 75

It is also possible to repeat strings by using the * operator:

greeting * 3 # Output: Hello!Hello!Hello!

Numeric: Integer and Float

Integers are whole numbers from negative infinity to infinity. There are no limits to the length of an integer value, except the amount of available memory. All decimal digits without a prefix will be treated as decimal numbers. To use another base, a prefix must be added to the integer value. The prefix for binary numbers using the base 2 is 0b or 0B, to use octal numbers with the base 8 add 0o or 0O, and for hexadecimal numbers with the base 16 add 0x or 0X. 

Float (for floating point number) values end with a decimal figure, e.g. 2.75. The difference between integers and floats is very important for division. Using the division operator / always results in a float:

6 / 3 # Output: 2.0
6 / 3.0 # Output: 2.0
6.0 / 3 # Output: 2.0
6.0 / 3.0 # Output: 2.0

Using integer division with // results in an integer, if both dividend and divisor are integers, and in a float in all other cases. For the numbers from the above example, not much will change. However, if the result of an integer division is not a whole number, it will always be rounded towards the lesser integer value. Integer division is therefore also called floor division.

6 // 4 # Output: 1
6.0 // 4 # Output: 1.0

Boolean

Objects of Boolean type can have one of two values: True or False. Booleans can be used both in conditional and comparison expressions.

# Comparison expressions
x = 5
y = 10

x < y # Output: True
x > y # Output: False
x + 7 > y # Output: True
X <= y # Output: True
X >= y # Output: False
x == y # Output: False
x != y # Output: True

# Conditional expressions
temperature_in_degrees_celsius = 20
sunny = temperature_in_degrees_celsius >= 20 # evaluates to True
cold = temperature_in_degrees_celsius <= 10 # evaluates to False

if sunny: 
    print('Wear a t-shirt')
elif cold:
    print('Wear a pullover and a jacket')
else:
    print('More information needed to make a suggestion!')

# Output: 'Wear a t-shirt'

Python Built-in non-primitive data structures

Python provides several built-in non-primitive data structures to store and organize a collection of values.

Dictionaries

In a dictionary, keys are mapped with values. Each combination of a key and a value is called a key-value pair or an item. While the values in a dictionary can be of any type and different values can be of different types, the keys must be hashable. Most often, strings and numbers are used as dictionary keys. The keys are immutable and unique. The dictionaries themselves are mutable. It is possible to add, delete, or change key-value elements. 

Create a dictionary:

# Create an empty dictionary eng_ger 
eng_ger = {}

# Typecast an empty dictionary ger_eng
ger_eng = dict()

# Create a dictionary from two iterables
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
weekday_numbers = [1, 2, 3, 4, 5, 6, 7]

# zip both lists
weekdays_with_numbers = dict(zip(weekdays, weekday_numbers))
print(weekdays_with_numbers) # Output: {'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6, 'Sunday': 7}

Adding, replacing, and deleting items:

# Add multiple key-value pairs to an empty dictionary
eng_ger = {'car': 'Automobil', 'house': 'Haus', 'cat': 'Katze'}
print(eng_ger) # Output: {'car': 'Automobil', 'house': 'Haus', 'cat': 'Katze'}

# Add a key-value-pair to an existing, non-empty dictionary
eng_ger['dog'] = 'Hund'
print(eng_ger) # output: {'car': 'Automobil', 'house': 'Haus', 'cat': 'Katze', 'dog': 'Hund'}
# Modify the value of an existing key
eng_ger['car'] = 'Auto'
print(eng_ger['car'] # Output: Auto

# Remove key-value pairs from a dictionary
del eng_ger['car']
print(eng_ger) # output: {'house': 'Haus', 'cat': 'Katze', 'dog': 'Hund'}  

# Remove all items from a dictionary
eng_ger.clear()
print(eng_ger) # Output: {}

Check whether a key or a value is contained in a dictionary:

# Check if a key is contained in a dictionary with the in keyword
print('mouse' in eng_ger) # Output: False

# Check if something appears as a value in a dictionary
values_in_dict = list(eng_ger.values()) # convert into list
print('Katze' in values_in_dict) # Output: True

Iterate over keys, values, and key-value pairs in dictionaries:

villains = {'Star Trek': 'The Borg', 'Star Wars': 'The Emperor', 'Harry Potter': 'Lord Voldemort', 'Lord of the Rings': 'Sauron'}

# iterate over the keys short version
for franchise in villains:
    print(franchise)

# Output:
Star Trek
Star Wars
Harry Potter
The Lord of the Rings
# iterate over the keys long version
For franchise in villains.keys():
    print(franchise) # Output: same as above

# iterate over the values
for villain in villains.values(): # the values() function must be called
    print(villain)

# Output:
The Borg
The Emperor
Lord Voldemort
Sauron

# iterate over the key-value pairs
for key, value in villains.items():
    print(f'Key: {key}, Value: {value}')

# Output:
Key: Star Trek, Value: The Borg
Key: Star Wars, Value: the Emperor
Key: Harry Potter, Value: Lord Voldemort
Key: Lord of the Rings, Value: Sauron

Get the number of key-value pairs in a dictionary:

# Get the number of key-value pairs in a dictionary
print(len(en_ger) # Output: 3

Merge multiple dictionaries into one dictionary:

villains = {'Star Trek': 'The Borg', 'Star Wars': 'The Emperor', 'Harry Potter': 'Lord Voldemort', 'Lord of the Rings': 'Sauron'}
more_villains = {'Star Trek TOS': 'Khan', 'Fantastic Beasts': 'Grindelwald', 'Star Wars': 'Darth Sidious'}

# In case of overlapping keys between the dictionaries, the newest value will be assigned to the key

# merge dictionaries with the update() function
villains.update(more_villains) # the villains dictionary is updated
print(villains)
# Output:
{'Star Trek': 'The Borg', 'Star Wars': 'Darth Sidious', 'Harry Potter': 'Lord Voldemort', 'Lord of the Rings': 'Sauron', 'Star Trek TOS': 'Khan', 'Fantastic Beasts': 'Grindelwald'}

# merge dictionaries with unpacking
combined_villains = {**villains, **more_villains} # a new dictionary is created and contains all values from the villains + more_villains dictionaries
print(combined_villains) # Output: same as above

# merge dictionaries with the dict() constructor
villains_combined = dict(villains, **more_villains) # the new dictionary takes the villains dictionary and combines it with the unpacked items of the more_villains dictionary
print(villains_combined) # Output: same as in the first example

Lists

Lists can contain zero or more items of different types. Like dictionaries, lists are mutable. Unlike dictionaries, the items in a list are indexed by their position, starting at 0. Lists can be sorted, reversed, sliced, and concatenated.

# create an empty list
friends = []
pets = list()

# create a list with some items
favourite_colours = ['blue', 'black', 'orange']

Add and remove items:

# add an item at the end of a list
favourite_colours.append('green')
print(favourite_colours)
# Output: ['blue', 'black', 'orange', 'green']

# insert an item at a given position
favourite_colours.insert(1, 'yellow')
print(favourite_colours)
# Output: ['blue', 'yellow', 'black', 'orange', 'green']

# extend a list by appending another list
more_colours = ['red', 'grey', 'silver', 'purple']
favourite_colours.extend(more_colours)
print(favourite_colours)
# Output: ['blue', 'yellow', 'black', 'orange', 'green', 'red', 'grey', 'silver', 'purple']

# remove an item value from a list
favourite_colours.remove('yellow')
print(favourite_colours)
# Output: ['blue', 'black', 'orange', 'green', red', 'grey', 'silver', 'purple']

# remove the last item from a list
favourite_colours.pop()
print(favourite_colours)
# Output: ['blue', 'black', 'orange', 'green', red', 'grey', 'silver']

# remove an item at a given position from a list
favourite_colours.pop(3)
print(favourite_colours)
# Output: ['blue', 'black', 'orange', 'red', 'grey', 'silver']

# remove all items from a list
more_colours.clear()
print(more_colours)
# Output: []

Sort and reverse:

# sort a list alphabetically
favourite_colours.sort()
print(favourite_colours)
# Output: ['black', 'blue', 'grey', 'orange', 'red', 'silver']

# reverse a list
favourite_colours.reverse()
print(favourite_colours()
# Output: ['silver', 'red', 'orange', 'grey', 'blue', 'black']

Count:

# return the number of items in a list
print(len(favourite_colours)
# Output: 6

# return the number of occurrences of a specified value
print(favourite_colours.count('grey'))
# Output: 1

Tuples

Like lists, the values in a tuple are indexed by integers, and tuples can contain elements of different types. The most important difference is that tuples are immutable. This means there are fewer functions available for tuples than for lists, because tuples can’t be modified. Why should tuples be used if they seem to be a light version of a list? 

  • Tuples use less space than lists
  • They can’t be changed by mistake
  • They can be used as dictionary keys. This allows us to get a sorted version of a dictionary
  • They are comparable

Create tuples:

# Enclose tuples in parentheses to make them quickly identifiable
vowels = ('a', 'e', 'i', 'o', 'u')

# When creating a tuple with a single element, a final comma has to be included to prevent it from being treated as a string
not_a_string = ('a',)

Sets

Sets can consist of zero or more elements and can contain elements of different types. Sets are mutable and unordered collections that don’t allow duplicates. They are mostly used to test whether a value exists in the set, and to compute the union, intersection, difference, and symmetric difference of two sets.

Create sets:

vowels = {'a', 'e', 'i', 'o', 'u'}

# use the set() constructor for empty sets to avoid creating an empty dictionary
empty_set = set()

Set methods:

# test whether a value exists in a set
'y' in vowels
False

# add a single item
vowels.add('y')
print(vowels)
# Output: {'u', 'y', 'o', 'e', 'i', 'a'}

# add multiple items as a list
vowels.update('x', 'z', 'k')
print(vowels)
# Output: {'z', 'e', 'y' 'k', 'a', 'x', 'u', 'i', 'o'}

# remove a single item
vowels.discard('y')
print(vowels)
# Output: {'k','z', 'e', 'a', 'u', 'i', 'x', 'o'}
vowels.discard('x')
vowels.discard('z')
vowels.discard('k')

name = set('oscar')
# check for values in both sets
print(name.intersection(vowels)
# Output: {'o', 'a'}

# check for values that are in either set or both
print(name.union(vowels)
# Output: {'o', 'r', 'y', 'c', 'a', 'i', 'e', 'u', 's'}

# check for values that are in the first set but not the second
print(name.difference(vowels)
# Output: {'r', 's', 'c'}

# check for values that are in one of the sets, but not both of them
print(name.symmetric_difference(vowels)
# Output: {'r', 'y', 'c', 'e', 'u', 's', 'i'}

Python Libraries

A Python library is a reusable collection of code or modules (a file with Python code in it) that can be used in programs or projects. The advantage lies in not having to write the code again and again. It is possible to simply import either separate functions or complete modules into our programs to make them available.

# import only the needed method
From math import sqrt

# import the complete module with all methods
import math

Another advantage is not to reinvent the wheel every time, and instead to use already existing and proven code.

The Python standard library

The Python core distribution contains the Python standard library with more than 200 modules. These modules allow access to basic system functionality and core modules. Some of the most important modules and some of their included functions are listed below. The built-in function dir(<module>) returns all module functions in a list. Use help(<module>) to see a manual page from the module’s docstrings.

The os module

The functions in the os module allow interactions with the operating system.

import os

os.chdir('<path of directory>') # change current working directory
os.getcwd() # return the current working directory
os.listdir() # list the files and directories in the current working directory

The math module allows access to the mathematical functions.

import math

x = 3.75

math.ceil(x) # return the smallest integer greater than or equal to x. Output = 4
math.floor(x) # return the largest integer less than or equal to x. Output = 3
math.sin(x) # return the sine of x radians. Output = -0.5715613187423437
math.sqrt(x) # return the square root of x. Output = 1.9364916731037085

The random module is used for random selections.

import random

random.random() # returns a random float
random.randrange(12)) # returns a random integer in the range from 0 - 12
random.sample(range(100), 5)) # returns a list of 5 integers in the range from 0 - 100

Other modules provide tools for string pattern matching (import re), the calculation of statistical properties (import statistics), sending mail (import smtplib), manipulating dates and times (import datetime), and writing tests for functions or units (import doctest, import unittest).

Additionally, there are over 137,000 Python libraries available. The Python Package Index (PyPi) is a repository where users can find, install, and distribute Python software.

Scott Böning, Code Institute Graduate

Experience Software Development

Don’t let the information above phase you. If you’ve landed on this page, it’s a good start. If you’re new to software development and want to learn some basic programming, register for our free 5 Day Coding Challenge through the form below. If you’ve already done the coding challenge, we do teach Python as part of our Full Stack Software Development Programme. Click here to find out more.

Git Merge  

The git merge command enables the developer to combine the several development lines produced by the git branch into a single branch.   Git In Git, each developer’s active version of the software is also a source that can include the complete history of all modifications rather than having just one location for it, as is […]

Git Rebase  

Rebase is a Git action that allows users to write the commits from one branch of Git to another. The Git tool called rebase helps merge updates from one branch to another. The act of integrating or transferring a series of commits on top of a fresh base commit is known as rebasing. The linear […]

The Semantic Web

The semantic web provides more context to websites so that not only humans but also machines can interpret the purpose of the content and data on the web to fetch and deliver coherent results.  Why the Semantic Web? Days of looking through a plethora of books in search of a specific piece of information are […]