Python Cheat Sheet

The only "True" language

#Functions

Basic Function & Return-statement

def increment(x):
    return x+1

result = increment(2)
print(result) # 3

Erros with Functions

def hello(name): 
    print("hello " + name)
    
hello("Max", 23) // error
Python cares which parameters are expected and which are really present. If one parameter is passed too much, an error occurs. Just like when one parameter is expected too much.

Arbitrary Arguments

def printPeople(*people):
    print(people)

printPeople("Max", "Anna")
# ('Max', 'Anna')
If you do not want to define how many arguments are passed, you can put a "*" before the parameter. This single parameter then contains a tuple of arguments, which are passed.

Lambda Functions

# basic syntax:
lambda arugments: return-expression

double = lambda x: x * 2

print(double(2)) # 4
Lambda functions are anonymous functions without the def-keyword. They are usually used as high-order-functions, i.e. as functions which get another function as parameter.

Lambda Functions - 2 Arguments

multiply = lambda x, y: x * y
    
print(multiply(2, 3)) # 6
Lambda Functions are not limited to just one argument / parameter. You can add more than one, by separating them with a comma

#Strings in Python

Converting Number to String

age = 24
print("Max is " + age)
# error - we cannot combine datatypes in print()
age = 24
print("Max is " + str(age))
# 'Max is 24'
The str() functions converts something to a string.

Replacing something in a String

age = 24
text = "Anna is x years old"
print(text.replace("x", str(age)))
# 'Anna is 24 years old'
The replace() function must be applied to a string, then replaces 'x' anywhere with age, converted to a string.

F-Strings in Python

age = 24
name = "Max"
print(f"{name} is {age} years old")
# 'Max is 24 years old'
F-Strings make it possible to print a variable within a string.

#Python Loops

For-Loop through a List

ages = [23, 21, 26]
for age in ages: 
    print(age)
# 23, 21, 26
age automatically takes the values in the list. It is not the counter variable!

For-Loop in a Range

for i in range(0, 3):
    print(i)
# 0, 1, 2
ages = [23, 21, 26]
for i in range(0, 3):
    print(ages[i])
# 23, 21, 26
In this loop, i is the counter variable. We can use it as the index when going through a list of elements. Range starts with the first param (0), and ends just before the last param (3), so with 2.

Looping through a List

ages = [23, 21, 26]
for i in range(0, len(ages)):
    print(ages[i])
# 23, 21, 26
len() returns the length, which is the number of elements in the list. If we start counting at 0, because 0 is the first index, we can go through all entries.

While-Loop

ages = [23, 21, 26]
counter = 0
while counter < 3:
    print(ages[counter])
    counter = counter + 1
# 23, 21, 26
The while-loop is executed as long as the condition is true. With each execution we increase the counter-variable by 1.

Continue

for i in range (0, 4):
    if i == 2:
        continue
    print(i)
# 0, 1, 3
Continue skips a loop under a certain condition. The print function is not executed if i = 2.

Break

for i in range (0, 4):
    if i == 2:
        break
    print(i)
# 0, 1
Break stops the loop as soon as a certain condition is fulfilled.

#In & Output

Reading Command-Line Input

name = input("Enter a name: ")
name # what the user entered
print(input("Enter a name: "))
The input function returns what the user entered, we can save it in a variable.

Print something on the command line

print("Hello!") # "Hello!"
print(23)
print("Max is " + 23 ) # error
print("Max is " + str(23))
With the print-function we can print out something. We can print a number, a string and so on, but not both combined - that's why we convert that number to a string.

Reading a file

textFile = open("text.txt", "rt")
print(textFile.read())
# prints what is inside of the text.txt

#Lists

What are Lists in Python?

Lists are not Arrays, but in Python you almost always use a list of what you would use arrays for in other languages.
Lists can be sliced, are mutable, can store data, have an index, can be iterated through, can hold data of different types.

A basic List in Python

ages = [23, 21, 26]
print(ages)
# [23, 21, 26]
# Lists can hold multiple data types:
randomData = ["car", 3.141, math.pi]

Element Indices

ages = [23, 21, 26]

ages[0] # 23
ages[1] # 21

ages[-1] # 26
ages[-2] # 21
It is counted from left to right, from 0. It is also possible to use a negative index, in which case it counts from right to left. It is counted from -1.

Add & Remove from List - Append & Pop

ages = [23, 21, 26]
# adds a new element:
ages.append(29)
# [23, 21, 26, 29]

# removes the last element:
ages.pop()
# [23, 21, 26]
Append adds an element to the position (len + 1). Pop removes the last element, so the element with the highest numerical position.

Constant List Range

ages = [23, 21, 26]

print(ages[0:2])
# [23, 21]
# starting with 0, stopping 
# one element before 2
Instead of specifying an index, we can specify a range of indexes.

List Range - starting with x

ages = [23, 21, 26, 24, 34, 21, 31]

print(ages[:2])
# [23, 21]

print(ages[5:])
# [21, 31]
The first Print function outputs all elements up to position 2 (not included) from the beginning.
The second outputs all elements from position 5 (not included) to the end.

#Miscellaneous

Sleep - pausing the execution

import time

print("now")
time.sleep(2)
print("after 2 seconds")