Conditional Tests (Comparisons) List comprehensions (to create lists)
Python Cheat Sheet Conditional tests evaluate to whether a statement is True or False. even_numbers = [2*x for x in range(10)]
Conditional tests odd_numbers = [2*x+1 for x in range(10)]
Expressions and Variables 1 < 2 # True divby3 = [x for x in range(100) if x%3==0]
Python evaluates expressions. The results can be stored in variables, 1+1 >= 2 # True Conditional tests with lists
which can be reused. Spaces around operators are optional! 1 < 2 < 3 # True (chaining) 2 in numbers # True
Simple mathematical expressions 1 == 1 # True: 1 equals 1 17 in numbers # False
1 + 1 # evaluates to: 2 Note: Double equal signs (==) have to be used for equality testing! 'Charlie' not in names # False
# Text after ‘#’ is a comment (ignored by Py) 1 != 2 # True: 1 is not equal 2 Removing items from lists
1+2*3 # 7 Boolean expressions numbers = [1,2,3,4,5,6]
(1+2)*3 # 9 x = 7 numbers.remove(4) # now: [1,2,3,5,6]
5**2 # 25 (power) x < 10 or x > 15 # True del numbers[2] # now: [1,2,5,6]
Division x < 10 and x > 7 # False del numbers[3:] # now: [1,2]
5/2 # 2.5 x < 10 and not x > 7 # True Copying lists
5//2 # 2 (integer division!) x = [1,2,3]
5 % 2 # 1 (modulo, remainder) Lists y = x # y refers to the same list as x
Lists are a container for data. They contain multiple items in a
Variables y[0] = 10 # modify y
particular order.
x = 2 # Assignment: x is now 2 print(x) # [10,2,3] – x was modified, too!
Creating a list
y = 1+1 # y is now 2 z = x[:] # z is a copy of x
numbers = [1,2,3,4,5]
z = x + y # z is now 4 z[0] = 5 # modify only z, not x
names = ['Alice', 'Bob', "Charlie"]
empty_list = [] Length of a list
Strings and Printing lst = [2,4,6,8]
Strings are sequences of characters; a representation of text. Printing
Get items from a list (indexing)
print(names[0]) # Alice len(lst) # 4
refers to the output of text from the program.
Hello world print(names[2]) # Charlie
print(numbers[-1]) # 5 ([-1] -> last item)
User Input
print('Hello world!')
Your programs can prompt (ask) the user to enter a value. The value is
print("Hello world!") names[0] = 'Al' # ['Al', 'Bob', 'Charlie'] always stored as a string (i.e., text) and you may need to convert it.
Note: Only straight single ( ' ) or double ( " ) quotes can be used (not Adding items to a list Prompting for a value
mixed)! Backticks and accents ( ´ or ` ) will not work. numbers.append(6) name = input("What's your name? ")
Hello world with variables more_names = ['Dave', 'Eve'] Note, how the careful use of " and ' in the previous line allows the
msg = 'Hello world!' names.extend(more_names) printing of the character '
print(msg) [1,2] + [3,4] # [1,2,3,4] print('Hello ' + name)
String concatenation Slicing a list (getting a range from a list) Prompting for a numerical value
first = 'Albert' names[2:4] # ['Charlie', 'Dave'] age = input('How old are you? ')
last = 'Einstein' numbers[4:5] # [5] age = int(age) # Convert to integer number
full_name = first + ' ' + last numbers[4:] # [5, 6]
print(full_name) # Albert Einstein numbers[0:5:2] # [1,3,5] (step: 2) pi = input("What's the value of pi? ")
print(first, last) # same result numbers[::-1] # [6,5,4,3,2,1] (step: -1) pi = float(pi) # Convert to decimal number
If-statements Functions Modules
If-statements allow conditional execution of your code. You can reuse code by defining functions (similar to print(…) ) Python comes with an extensive standard library of useful functions,
Simple tests Defining and invoking (calling) functions grouped into modules. Refer to the online documentations!
if age >= 18: def say_hi(): Importing a module
print('You can vote!') print('Hi!') import math # Now we can use math functions
If-elif-else case distinctions say_hi() math.exp(1) # 2.71828…
if age < 4: # Do not forget the colon (:) say_hi() math.cos(0) # 1.0
ticket_price = 0 Defining functions with parameters Importing functions from a module
elif age < 18: # You can use multiple elif def greet(name): from math import exp as e
ticket_price = 10 print('Hi, ' + name + '!') from math import cos, pi
else: greet('Alice') # prints: Hi, Alice! e(0) # 1.0 (no math. needed)
ticket_price = 15 greet('Bob') # prints: Hi, Bob! cos(pi) # -1.0
Multiple parameters
Loops def print_sum(x, y): numpy
Loops allow repeating certain lines of your code a certain number of A module to perform numerical operations more easily.
print(x+y)
times or while a condition is fulfilled. A basic example
print_sum(1, 2) # prints: 3
For-loop import numpy as np
Return values
lst = [] # Create values from 0 to 10 with step 0.01
def add(x,y):
for i in range(5): x = np.arange(0, 10, 0.01)
return x + y
lst.append(i) y = np.exp(x) # Apply exp to all x
z = add(1,2) # z is now 3
print(lst) # [0,1,2,3,4]
Default parameters
While-loop matplotlib/pyplot
def less(x, y=1):
lst = [] Visualizing (plotting) data graphically.
return x – y
x = 1 A basic example (cont. from numpy above)
z = less(17) # z is now 16
while x < 10: from matplotlib import pyplot as plt
z = less(17, 2) # z is now 15
x *= 2 # same as: x = x * 2 plt.figure()
print(lst, x) # [1,2,4,8] 16 plt.plot(x, y)
Error Handling
Iterating over elements of a list plt.show()
Some conditions (e.g. user input) might bring your program into a
my_dogs = ['Rex', 'Snoopy', 'Rufus'] state, where it cannot continue as normal (a crash).
for dog in my_dogs: Catching errors
print(dog + ' is my dog!') age = input("What's your age?")
try: # Place below what could go wrong:
for i, dog in enumerate(my_dogs): age=int(age)
print(dog + ' is my dog no. ' + str(i)) except:
print('You did not enter a number!')
Version 1.1 (Nov 2019)
else:
Eike Moritz Wülfers
Universitäts-Herzzentrum Freiburg · Bad Krozingen
print('Thank you!')