Python

Python

A resource collection around the programming language Python

Stefan Schneider Mon, 04/04/2022 - 14:22

Dictionaries (Cheat Sheet)

Dictionaries (Cheat Sheet)

Dictionaries are data structures which map keys to values. Lists can be thought of as dictionaries with integer keys within a certain range. Dictionaries can be indexed like lists, using square brackets containing keys.

Examples

speed = {"Mercedes": 200, "BMW": 210, "Volkswagen": 220}
print(speed["Mercedes"])
print(speed["Volkswagen"])

and empty dictionary

dic = {}

Important: keys have to be immutable

Searching for keys

Examples

print("Mercedes" in speed)
print("Airbus" not in speed)

Function get()

Get a value with the get function:

print(speed.get("BMW")

Return a default value if the key does not exist:

print(speed.get("Fiat":250)

 

Stefan Schneider Tue, 05/03/2022 - 17:03

Exceptions and their handling (Cheat Sheet)

Exceptions and their handling (Cheat Sheet)

Handling an Exception

try:
   a = 2
   b = 0
   print( a/b )
   print(" Done with division...")
except ZeroDivisionError:
   print (" A ZeroDivisionError exception happened...")
finally:
   print("This line will run no matter what")

The final block will be handled no matter whether an exception will be handled or not

Handling of multiple exception types

try:
   var = 10
   print(var + " hi")
   print(var / 2)
except ZeroDivisionError:
   print("Division by zero")
except(ValueError, TypeError):
   print("Houston we have a problem...")

Catch all errors

try:
   text = ("This is a string")
   print(word / 0)
except:
   print("An exception happened")

Raise an exception on your own

print("Get ready!")
raise ValueError
print("No one executed me...")

Re-raise an exception

try:
   number = 7 / 0
except:
   print("Houston we have a problem...")
   raise

 

Stefan Schneider Mon, 04/11/2022 - 13:48

Function and Modules (Cheat Sheet)

Function and Modules (Cheat Sheet)

Example

Functions need to be declared in the file before they can be used

def my_function():
   print("I")
   print("am")
   print("a")
  print("function")

my_function()

Parameter and variables declared in a function are local to the function

Returning values

def min(alb):
   if a < b :
      return a
   else:
      return b

print min(5,8)

 

Stefan Schneider Tue, 04/05/2022 - 16:24

Functional Programming

Functional Programming

Higher-Order Functions

Use a function as parameter. Example:

def do_twice(func,arg):
   return func(func(arg))

def double_it(arg):
   return arg * 2

print(do_twice(double_it,3))

Anonymous Functions(Lambdas)

Example:

def a_func(f, arg):
   return f(arg)

result = a_func(lambda k: k+k, 5)
print(result)

Use the

  • lambda keyword
  • the parameter variable,
  • an expression to be processed
  • a comma
  • and the value to be passed

Another example:

def add_six(x):
   return  x + 6
print(add_six(4))

print((lambda x:x + 6) (4))

Assign a Function to a Variable

Example

vat = lambda x: x * 1.19
print(vat(2))

Functions

map Function

def double_it(x):
   return x * 2

nums = [1, 2, 3, 4, 5]
res = list(map(double_it, nums))
print (res)

Alternative with an anonymous function:

nums = [1, 2, 3, 4, 5]
res = list(map(lambda x: x*2, nums))
print (res)

filter Function

Example:

nums = [1, 2, 3, 4, 5]
result = list(filter(lambda x: x%2==1, nums))
print (result)

Parameters

  • lambda variable
  • a function which returns a boolean

Generators

Example:

def counting():
   i = 0
   while i < 10:
      yield i
      i += 1

for i in counting():
   print(i)

Generators are iterables. They can be used in while and for loops.

yield defines a generator which replaces the return of a function. It does not destroy local variables

Interesting: Generators can be infinite since they don't have memory restrictions.

def nums(x):
   for i in range(x):
      if i % 3 == 0:
         yield i

print(list(nums(20)))
Stefan Schneider Thu, 05/05/2022 - 14:21

Lists and Ranges (Cheat Sheet)

Lists and Ranges (Cheat Sheet)

Examples

words = ["This", "is", "a", "list","of", "strings"]
print (words[0])
print (words[1])
print (words[2])
print (words[3])
print (words[4])
print (words[5])

print(words)

empty_list =[]
print(empty_list)

List with multiple types and dimensions

num = 3
my_list = ["a string", 2,[0, 1, 2, num], 3.14]
print(my_list[2][1])
print(my_list[3])

Indexing characters in strings like lists

str = "I am a string"
print(str[3])

Replicating lists like strings

li = [3, 2, 1, 0]
print (li * 3)

List operations

words = ["This", "is", "a", "list","of", "strings"]
print("is" in words)
print("is-not" in words)

numbers = [0, 1, 2, 3]
if 2 in numbers
   print("found it"
else:
   print(" did not find it")

for var in numbers:
   print(var)

List functions

numbers = [0, 1, 2]
numbers.append(4)
print(numbers)
print(len(numbers))
the_index = 3
numbers.insert(the_index, 3)
print(numbers)
numbers.append(55)
print(numbers.index(55))

List Slices

Create a sublist from index 0 to index 2. The second index is not included!

print(numbers[0:2])

Take a slice from the begin of a list

print(numbers[:2])

Take a slice from a start index to the end of a list

print(numbers[1:])

A step as a third parameter

a = [0, 1,2,3,4,5,6,7,8]
print(a[2:6:2])

The first and the second parameter can be empty. It execute things from the start or through the end of the list

List Comprehensions

squares = [i**2 for i in range(6)]
print(squares)

A comprehension with an if condition

squares = [i**2 for i in range(10) if i%2 == 0]
print(squares)

List Functions

>>> numbers = [99, 88, 77, 66 ]
>>> if all([i < 55 for i in numbers]):
...    print("All elements are smaller than 55")
...
>>> if any([i == 88 for i in numbers]):
...    print("Found 88!")
...
Found 88!
>>> for k in enumerate(numbers):
...    print(k)
...
(0, 99)
(1, 88)
(2, 77)
(3, 66)

Ranges

Important: ranges create objects. They do not create lists

n = list(range(3))
print(n)
n = list(range(3,8))
print(n)
n = list(range(4, 10, 2))
print(n)
  • 1 parameter: create an object which starts with 0 and ends one number below the argument
  • 2 parameter: create an object which starts with first argument and ends one number below the second argument
  • 3 parameter:create an object which starts with first argument and ends one number below the second argument. Third argument is step function which determines the intervall
Stefan Schneider Tue, 04/05/2022 - 09:17

Loops and Branches (Cheat Sheet)

Loops and Branches (Cheat Sheet)

if statement

if 9 > 5:
   print(" 9 is great than 5")

print(" End of Program")

Two important things

  1. A colon":" is required after the condition
  2. Ident with at least one space
x = 1
y = 2
if x > y:
   print(" x is larger")
else:
   print(" x is not larger")

Important: The colon after the key word else!

number = 3
if number == 1:
   print("one")
elif num == 2:
   print("two")
elif num == 3:
   print("three")
else:
   print("something different")

while loop

i=1
while i<=5:
   i = i + 1

print(i)

infinite loops

i = 0
while True:
   print(i)
   if i >= 6
      print("leave the loop"
      break

print("Done...")

continue will end a block in a loop. It will force the program counter to jump back to the next test in the while condition

i = 0
while i<6:
   i += 1
   if i == 3:
      print(" Will skip rest of block...")
      continue
   print(i)

for Loop

days =["Monday", " Tuesday", "Wednesday", "Thursday", " Friday", "Saturday", "Sunday"]
for day in days:
   print(day +"!")

for loops can iterate over strings

str = "this is a string"
count=0
for x in str:
   if(x == "t"):
      count += 1

print(count)

break and continue can be used in the for block

Stefan Schneider Mon, 04/04/2022 - 14:24

Numeric Functions

Numeric Functions

Examples

>>> print(min(1, 2, 3, 4))
1
>>> print(max(1, 2, 3, 4))
4
>>> print(sum([1, 2, 3, 4]))
10
>>> print(max([1, 2, 3, 4]))
4
>>> print(abs(-3))
3
Stefan Schneider Wed, 05/04/2022 - 11:58

Strings (Cheat Sheet)

Strings (Cheat Sheet)

String Formatting

>>> number = [10, 11, 12]
>>> text = "Numbers: {0} {1} {2}".format(number[0],number[1], number[2])
>>> print(text)
Numbers: 10 11 12

Joining Strings with a Separator

>>> print(" && ".join(["apple pie","motherhood"]))
apple pie && motherhood

Replacements

>>> print("Good morning !".replace("morning", "afternoon"))
Good afternoon!

Check for the Ending

>>> print("Good morning!".endswith("morning!"))
True
>>> print("Good morning!".endswith("morning"))
False

Check for the Beginning

>>> print("Good morning".startswith("Lousy"))
False

Capitilize Strings and lower them as well...

>>> print("Good morning".upper())
GOOD MORNING
>>> print("Good morning".lower())
good morning

Split Strings and turn them into Lists

>>> print("Motherhood, and, apple pie".split(", "))
['Motherhood', 'and', 'apple pie']
Stefan Schneider Wed, 05/04/2022 - 11:28

Tuples (Cheat Sheet)

Tuples (Cheat Sheet)

Tuples are similar to lists:

Lists Tuples
mutable immutable
use square brackets to identify use parentheses to identify

Tuples tend to be faster since they are immutable

Example

sentence = ( "This", "is", "a", "tuple")
print(sentence[1])
sentence[3] = "phrase"

An empty tuple:

sentence = ()
Stefan Schneider Tue, 05/03/2022 - 17:33

Working with Files (Cheat Sheet)

Working with Files (Cheat Sheet)

Opening files examples...

afile = open("filename.txt")
afile.close()
afile = open("filename.txt", "w") // In read mode
afile.close()
afile = open("filename.txt", "r") // In write mode
afile.close()
afile = open("filename.txt"), "wb") // In binary write mode
afile.close()
afile = open("filename.txt"), "rb") // In binary read mode
afile.close()

Reading a file

The following code reads

file = open("file.txt", "r")
cont = file.read()
print(cont)
file.close()

Reading a number of characters

file = open("file.txt", "r") 
print(file.read(2))
print(file.read(3))
print(file.read(4))
file.close()

Example reading a file

The following reads chunks of four characters

file = open("file.txt", "r")
for i in range(21):
   print(file.read(4))
file.close()

Empty strings will be returned after the end will  be reached.

Reading lines from text file

The following codes reads a file into a list of string

file.open(file.txt)
print(file.readlines())
file.close()

Writing Files

A file will be created if it does not yet exist.
The content of an existing file will be deleted.

file.open("file.txt","w")
file.write("Write this text to the file")
file.close()

Tracking of bytes written

text = "Hello world"
file.open("file.txt","w")
amount_bytes = file.write(text)
print(amount_bytes)
file.close()

Using the "with" statement

with open("file.txt") as f:
   printf(f.read())
Stefan Schneider Mon, 04/11/2022 - 14:37