Module Python

Image credit: Unsplash: Chris Ried
Table of Contents

Get Started with Python

In this module I will learn how to code with Python. You will find several tasks about Python in this publication.

Write a Hello World-Program

Input
# Hello World-Programm
print("Hello World")

response = "Hello Back"

print(response)
Output
Hello World
Hello Back


Different types of comments

In Python you have the possibility to write single-line comments or multi-line comments.

# I'm a single-line comment

"""
I'm
a
multi-line
comment
"""


Primitive Types

Assign each primitive Type to a variable

Input
#This is an integer Variable
integerVariable = 1

#This is a floating point Variable
floatVariable = 1.0

#This is a string Variable
stringVariable = "Amanoxian"

#This is a boolean Variable
booleanVariable = True

typeOfIntegerVariable = type(integerVariable)
typeOfFloatVariable = type(floatVariable)
typeOfStringVariable = type(stringVariable)
typeOfBooleanVariable = type(booleanVariable)

print(typeOfIntegerVariable)
print(typeOfFloatVariable)
print(typeOfStringVariable)
print(typeOfBooleanVariable)
Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>


String-Methods

Use different methods on a string

❯ capitalize()

Input
#define a string and capitalize the first letter
a = "hello world"
a = a.capitalize()

print(a)
Output
Hello world


❯ count()

Input
#define a string variable and count the number of a specific value
brand = ["Opel", "Toyota", "Audi", "Opel", "Kia"]
tot = brand.count("Opel")
pieces = " times"

print (str(tot)+pieces)
Output
2 times


❯ endswith()

Input
#define a string Variable and analyze the end with method endswith()
message = "Hello, my name is Python."
x = message.endswith(".")

print(x)
Output
True


❯ find()

Input
#define a string and find a specific value with method find()
message = "Hello, my name is Python."
x = message.find("y", 15, 20)
position = "Position "

print(position+str(x))
Output
Position 19


❯ lower()

Input
#define a string and change uppercase letters to lowercase with method lower()
message = "Hello, my name is Python."
x = message.lower()

print(x)
Output
hello, my name is python.


❯ replace()

Input
#define a string and replace a specific value with method replace()
message = "Hello, my name is Python."
x = message.replace("Python", "Xavier")

print(x)
Output
Hello, my name is Xavier


❯ split()

Input
#define a string and split up with method split()
message= "Hello, my name is Python."
x = message.split()

print(x)
Output
['Hello,', 'my', 'name', 'is', 'Python.']


❯ startswith()

Input
#define a string Variable and analyze the start with method startswith()
message = "Hello, my name is Python."
x = message.startswith("Salut")

print(x)
Output
False


❯ strip()

Input
#define a string and insert a strip with method strip()
dish = "spaghetti code"
x = dish.strip()

print("Of all dishes", x, "is my favorite")
Output
Of all dishes spaghetti code is my favorite.


❯ upper()

Input
#define a string and change lowercase letters to uppercase with method upper()
dish = "spaghetti carbonara"
x = dish.upper()

print(x)
Output
SPAGHETTI CARBONARA


Non-Primitive Types

Lists

● Implement a List
● The list should contain: an Integer, a String and a nested list
● Make a second list and merge both.

Input
#define two lists and merge them together
firstList = [1, "Python", [2, "I'm a nested list"]]
secondList = [3, "Keyboard", 3.1]

print(firstList+secondList)
Output
[1, 'Python', [2, "I'm a nested list"], 3, 'Keyboard', 3.1]


Arrays

● Make two numpy-Arrays with numbers.
● Sum those arrays together.

Input
#define two numpy arrays and sum those together
numpy1 = [1, 2, 3, 4, 5]
numpy2 = [5, 4, 3, 2, 1]

print(sum(numpy1 + numpy2))
Output
30


List- & Array-Methods

❯ append()

Input
#define a list and append an element with append()
elements = [1, "Python"]
elements.append(2)

print(elements)
Output
[1, 'Python', 2]


❯ clear()

Input
#define a list and clear all eith method clear()
fruits = ["strawberry", "apple", "orange"]

fruits.clear()

print(fruits)
Output
[]


❯ copy()

Input
#define a list and copy the elements in an other var with method copy()
fruits = ["strawbery", "apple", "orange"]

a = fruits.copy()

print(a)
Output
['strawbery', 'apple', 'orange']


❯ count()

Input
#define a list and count a specific element with count()
fruits = ["orange" , "lime", "orange", "apple", "orange"]
pieces = " times"

a = fruits.count("orange")

print (str(a)+pieces)
Output
3 times


❯ extend()

Input
#define a list an extend with an other list with method extend()
fruits = ["orange" , "lime", "orange", "apple", "orange"]
otherFruits = ["papaya", "melon"]

fruits.extend(otherFruits)

print (fruits)
Output
['orange', 'lime', 'orange', 'apple', 'orange', 'papaya', 'melon']


❯ index()

Input
#define a list and find the index of a specific element with method index()
fruits = ["orange" , "lime", "orange", "apple", "orange"]
c = fruits.index("apple")
position = "Position "

print (position+str(c))
Output
Position 3


❯ insert()

Input
#define a list and insert an element with method insert()
fruits = ["orange" , "lime", "orange", "apple", "orange"]
fruits.insert(0, "apple")

print (fruits)
Output
['apple', 'orange', 'lime', 'orange', 'apple', 'orange']


❯ pop()

Input
#define a list and delete a specific element with method pop()
fruits = ["orange" , "lime"]
fruits.pop(0)

print (fruits)
Output
['lime']


❯ remove()

Input
#define a list and remove an element with method remove()
fruits = ["orange" , "lime"]
fruits.remove("lime")

print (fruits)
Output
['orange']


❯ reverse()

Input
#define a list and reverse the order with method reverse()
fruits = ["orange" , "lime"]
fruits.reverse()

print (fruits)
Output
['lime', 'orange']


❯ sort()

Input
#define a list and sort alphabetically with method sort()
brands = ['Mercedes', 'Jeep', 'Audi','Kia']
brands.sort()

print(brands)
Output
['Audi', 'Jeep', 'Kia', 'Mercedes']


Tuples

● Implement a Tuple with 3 elements
● Change the tuple to a 4 elements structure. Add a 4th element.
● Join two Tuples.
● Explain a case where tuples are better than lists as a comment or demonstrate with an example
● Use all existing methods and demonstrate the usage. Explain the different parameters if they have params.

Input
#define a tuple with 3 elements
thisTuple = ("lime", "orange", "banana")

print(thisTuple)
Output
('lime', 'orange', 'banana')



You can’t insert new elements in created tuples because they have an immutable property. But you have the possibility to join serveral tuples in a new tuple. See below 🠗

Input
#define serveral tuples and join them
thisTuple = ("lime", "orange", "banana")
nextTuple = ("papaya", "apple")

joinTuple = thisTuple + nextTuple

print(joinTuple)
Output
('lime', 'orange', 'banana', 'papaya', 'apple')


Tuple-Methods

❯ count()

Input
#define a tuple and count a specific element with method count()
anothertuple = (2, 2, 2, 2, 3, 4, 5)

u = anothertuple.count(2)
times = " times"

print(str(u)+times)
Output
4 times


❯ index()

Input
#define a tuple and find the index of a specific element with method index()
fruits = ("orange" , "lime", "orange", "apple", "orange")
c = fruits.index("apple")
position = "Position "

print (position+str(c))

Output
Position 3

Whenever, we need to make sure that the data remains unchanged and write protected, then a tuple is the best option in Python.


Sets

● Implement a Set with 3 elements
● Add a duplicate value and then print the content. Explain what happens.
● Join two sets into one with .union()
● Explain a case where sets are better than lists as a comment or demonstrate with an example
● Use all existing methods and demonstrate the usage. Explain the different parameters if they have params.

Input
# 1. define a set with 3 elements + one similar
# 2. Join two sets into one with .union()

thisSet = {"lime", "lime", "orange", "banana"}
nextSet = {"hello", "I'm", "unordered"}

unionSet = thisSet.union(nextSet)

print(thisSet)
print(unionSet)
Output
{'lime', 'orange', 'banana'}
{'unordered', 'banana', 'hello', "I'm", 'lime', 'orange'}

Sets cannot contain duplicates, and they will simply disappear. That’s why we see the element “lime” only one time in the printout. Processing a set is faster than processing a list, because each element can only occur once. This allows us to use the hash function.


Set-Methods

❯ All methods

Input
#define a set and add an element with method add()
tuple1 = {"mouse", "rat", "cat"}
tuple1.add("dog")

print(tuple1)


#define a set and then clear it with method clear()
tuple1 = {"mouse", "rat", "cat"}
tuple1.clear()

print(tuple1)


#define a set and copy the elements in an other var with method copy()
tuple1 = {"mouse", "rat", "cat"}
tuple1copy = tuple1.copy()

print(tuple1copy)


#define two sets and show up the differences between them
#method difference()
a = {"Apple", "Strawberry", "Lime"}
b = {"Apple", "Microsoft", "Google"}
c = a.difference(b)

print(c)


#define two sets and show up the differences + clear the similar elements
#with method difference_update()
a = {"Apple", "Strawberry", "Lime"}
b = {"Apple", "Microsoft", "Google"}
a.difference_update(b)

print(a)


#define a set and clear an element with method .discard()
a = {"hello", "my", "name", "is", "Python"}
a.discard("Python")

print(a)

#define two sets and show up the similar elements with method intersection()
a = {"Apple", "Strawberry", "Lime"}
b = {"Apple", "Microsoft", "Google"}
c = a.intersection(b)

print(c)


#define two sets and remove elements in which are not present in both sets
#method intersection_update()
a = {"Apple", "Banana", "Cherry"}
b = {"Google", "Microsoft", "Apple"}
a.intersection_update(b)

print(a)


#define two sets and test if there are similar elements in the two sets or not
#method isthisjoint()
x = {"cat", "fish", "dog"}
y = {"instagram", "whatsapp", "pycharm"}
z = x.isdisjoint(y)

print(z)


#define two sets and check if both sets contain the similar elements
#method issubset()
a = {1, 2, 3}
b = {4, 5, 6, 3, 2, 0}
c = a.issubset(b)

print(c)


#define two sets and check if all items from the second set are present
#in the first set use the method issuperset()
a = {1, 2, 3, 4, 5, 6}
b = {3, 2, 1}
c = a.issuperset(b)

print(c)


#define a set and remove a random element with method pop()
d = {"Hello", "This", "Is", "Very", "Satisfying"}
d.pop()

print(d)


#define a set and remove a specific element with method remove()
d = {"Hello", "This", "Is", "Very", "Satisfying"}
d.remove("Is")

print(d)


#define two sets and show up the elements which are not present in both sets
#method symmetric_difference
a = {1, 2, 3, 4, 5, 6}
b = {3, 2, 1, 7, 8, 9, 10}
c = a.symmetric_difference(b)

print(c)


#define two sets and remove from the first set all elements which
#are present in both setsand add the remaining elements from the
#second set with method symmetric_difference_update
a = {1, 2, 3, 4, 5, 6}
b = {3, 2, 1, 7, 8, 9, 10}
a.symmetric_difference_update(b)

print(a)


#define two sets and create an union of them with method union()
brands = {"DC", "Nike", "Puma"}
things = {"bicycle", "car", "helmet"}

mixture = brands.union(things)

print(mixture)


#define two sets and update the first set with the elements from the second set
#method update()
brandsmixedwiththings = {"DC", "Nike", "Puma"}
things = {"bicycle", "car", "helmet", "DC", "Nike", "Puma"}
brandsmixedwiththings.update(things)

print(brandsmixedwiththings)
Output
{'mouse', 'rat', 'dog', 'cat'}
set()
{'mouse', 'rat', 'cat'}
{'Strawberry', 'Lime'}
{'Strawberry', 'Lime'}
{'hello', 'name', 'my', 'is'}
{'Apple'}
{'Apple'}
True
False
True
{'This', 'Satisfying', 'Very', 'Hello'}
{'This', 'Satisfying', 'Very', 'Hello'}
{4, 5, 6, 7, 8, 9, 10}
{4, 5, 6, 7, 8, 9, 10}
{'Puma', 'Nike', 'car', 'bicycle', 'helmet', 'DC'}
{'Nike', 'bicycle', 'car', 'Puma', 'helmet', 'DC'}


Dictionaries

● Implement a Dictionary that contains a key called “persons” with an empty list as value
● Call the list via the key. It should be empty
● Join two sets into one with .union()
● Call the list inside the dict and fill the embedded list it with new dictionaries. Each new dict should contain the following keys: “Name”, “Firstname” and “Age”.
● Create a second dict that contains a new key and a different value. Join the first dict with the new one.
● Explain a case where dicts are better than lists as a comment or demonstrate with an example
● Use all existing methods for dicts and demonstrate the usage. Explain the different parameters if they have params.

Input
#define a dictionary that contains a key called
#"person" with an empty list as value
#Call the list inside the dict and fill the embedded list it with new dicts.
#Each new dict should contain the following keys: “Name”, “Firstname” and “Age”.
#Create a second dict that contains a new key and a different value
#Join the first dict with the new one.

dict1 = {'person': []}
print(dict1['person'])

dict1 = {'person': [{'Name': 'Jeiziner',
                     'Firstname': 'Xavier',
                     'Age': 22}]}

dict2 = {'animal': [{'Name': 'Lennox',
                     'sex': 'male',
                     'age': 1,}]}
dict1.update(dict2)
print(dict1)
Output
[]
{'person': [{'Name': 'Jeiziner', 'Firstname': 'Xavier', 'Age': 22}],
 'animal': [{'Name': 'Lennox', 'sex': 'male', 'age': 1}]}

Processing a dictionary is faster than processing a list, because each key can only occur once. In a list the elements are accessed via indices, while in a dictionary the elements are accessed via key-values. This allows us to use the hash function.


Dictionary-Methods

❯ All methods

Input
#define a dictionary and clear the content with method clear()
dream = {
    "brand": "Audi",
    "model": "RS3",
    "year": 2016
    }

dream.clear()
print(dream)


#define a dictionary and copy the content to a new dictionary
#with method copy()
dream = {
    "brand": "Audi",
    "model": "RS3",
    "year": 2016
    }

car = dream.copy()
print(car)

#define a tuple with keys and then convert it to a dictionary
#with method fromkeys()
a = ('a', 'b', 'c')
b = 1

dict1 = dict.fromkeys(a, b)
print(dict1)


#define a dictionary and print a defined key with method get()
dream = {
    "brand": "Audi",
    "model": "RS3",
    "year": 2016
    }

print(dream.get("model"))


#define a dictionary and print a the dict_items with method items()
dream = {
    "brand": "Audi",
    "model": "RS3",
    "year": 2016
    }

print(dream.items())


#define a dictionary and print the involved keys with method keys()
dream = {
    "brand": "Audi",
    "model": "RS3",
    "year": 2016
    }

print(dream.keys())


#define a dictionary and delete the last added item with method popitem()
dream = {
    "brand": "Audi",
    "model": "RS3",
    "year": 2016,
    "Motorcode": "BAM"
    }

dream.popitem()
print(dream)


#define a dictionary and print a specific item with method setdefault()
#if the item does not exists, print the parameter from the method
dream = {
    "brand": "Audi",
    "model": "RS3",
    "year": 2016
    }

model = dream.setdefault("model", "S3")
print(model)


#define a dictionary and add a new item with method update()
dream = {
    "brand": "Audi",
    "model": "RS3",
    "year": 2016,
    }

dream.update({"Motorcode": "BAM"})
print(dream)


#define a dictionary and print the values from all keys
#with method values()
dream = {
    "brand": "Audi",
    "model": "RS3",
    "year": 2016,
    }

print(dream.values())
Output
{}
{'brand': 'Audi', 'model': 'RS3', 'year': 2016}
{'a': 1, 'b': 1, 'c': 1}
RS3
dict_items([('brand', 'Audi'), ('model', 'RS3'), ('year', 2016)])
dict_keys(['brand', 'model', 'year'])
{'brand': 'Audi', 'model': 'RS3', 'year': 2016}
RS3
{'brand': 'Audi', 'model': 'RS3', 'year': 2016, 'Motorcode': 'BAM'}
dict_values(['Audi', 'RS3', 2016])


Files

● Demonstrate on a file all modes.

Input
#different modes on files
#1. create a file
f = open("demofile.txt", "x")
f.close()

#2. write something in it
f = open("demofile.txt", "w")
f.write("I'm a new written textfile")
f.close()

#3. read and print the content
f = open("demofile.txt", "r")
print(f.read())
f.close()

#4. append a new file if it doesn't exists
f = open("demofile1.txt", "a")
f.close()

#2. write something in it
f = open("demofile1.txt", "w")
f.write("[]")
f.close()

#5. read the new file
f = open("demofile1.txt", "r")
print(f.read())
f.close()

#6. delete the generated files
import os
os.remove("demofile.txt")
os.remove("demofile1.txt")
Output
I'm a new written textfile
[]


● Explain or show the difference between: -f = open(“demofile.txt”, “rt”) / -f = open(“demofile.txt”, “rb”)

The “t” means that python reads the demofile.txt as a text. If you use the character “b”, then the demofile.txt is read as binary code. See below 🠗

Input
#binary
#1. create a file
f = open("demofile.txt", "x")
f.close()

#2. write something in it
f = open("demofile.txt","wb")
num = [5, 10, 15, 20, 25]
arr=bytearray(num)
f.write(arr)
f.close()

#3. read and print the content --> binary
f = open("demofile.txt", "rb")
print(f.read())
f.close()

#5. delete the generated file
import os
os.remove("demofile.txt")
Output
b'\x05\n\x0f\x14\x19'


● Create a new file with “hello” as text inside the file
● Edit the file, read its content and the rewrite it to “Hello World”
● Delete the file as a last action.

Input
#1. create a file
f = open("HelloWorld.txt", "x")
f.close()

#2. write something in it
f = open("HelloWorld.txt","w")
f.write("Hello")
f.close()

#3. read and print the content
f = open("HelloWorld.txt", "r")
print(f.read())
f.close()

#4. append some more text
f = open("HelloWorld.txt", "a")
f.write(" World")
f.close()

#5. read and print the content
f = open("HelloWorld.txt", "r")
print(f.read())
f.close()

#6. delete the generated file
import os
os.remove("HelloWorld.txt")
Output
Hello
Hello World


Arithmetic Operators

Test all operators on an integer, float, string, boolean

Input
#operators --> Integer
a = 2 + 2
b = 3 -1
c = 100 / 5
d = 5 // 2
e = 8 % 5
f = 2 ** 3
g = 3 * 3
x = ','

print(str(a)+x, str(b)+x, str(c)+x, str(d)+x, str(e)+x, str(f)+x, str(g))


#operators --> Float
a = 2.0 + 2.0
b = 3.0 -1.0
c = 100.0 / 5.0
d = 5.0 // 2.0
e = 8.0 % 5.0
f = 2.0**3.0
g = 3.0 * 3.0
x = ','

print(str(a)+x, str(b)+x, str(c)+x, str(d)+x, str(e)+x, str(f)+x, str(g))


#operators --> String
a = "A" + "B"

print(a)


#operators --> Boolean
a = True
d = False
x = ','

print(str(a + a) + x, str(a - a) + x, str(a / a) + x,
      str((a + b) // b) + x, str((a + b + b) % b) + x,
      str(b ** b) + x, str(a * b) + x)

#operators --> Lists
a = [1, 3.0, "String"]
b = [1.0, 3.0, True, False]

print(a + b)
Output
4, 2, 20.0, 2, 3, 8, 9
4.0, 2.0, 20.0, 2.0, 3.0, 8.0, 9.0
AB
2, 0, 1.0, 1.0, 1.0, 4.0, 2.0,
[1, 3.0, 'String', 1.0, 3.0, True, False]


What happens if you use combine datatypes? For example 5 * “lol”

Input
# Concatenation * 5
print(5 * "lol")
Output
lollollollollol


Relational Operators

Demonstrate all relational operators on different data-types

Input
#relational operators --> Integer
a = 2 < 3
b = 3 > 1
c = 100 <= 5
d = 5 >= 2
e = 8 % 5
f = 2 == 3
g = 3 != 3
x = ','

print(str(a)+x, str(b)+x, str(c)+x, str(d)+x, str(e)+x, str(f)+x, str(g))


#relational operators --> float
a = 2.0 < 3.0
b = 3.0 > 1.0
c = 100.0 <= 5.0
d = 5.0 >= 2.0
e = 8.0 % 5.0
f = 2.0 == 3.0
g = 3.0 != 3.0
x = ','

print(str(a)+x, str(b)+x, str(c)+x, str(d)+x, str(e)+x, str(f)+x, str(g))



#relational operators --> String
a = "A" == "B"

print(a)


#relational operators --> Boolean
a = True == True

print(a)


#relational operators --> Lists
a = [1, 3.0, "String"]
b = [1.0, 3.0, True, False]

print(a == b)
Output
True, True, False, True, 3, False, False
True, True, False, True, 3.0, False, False
False
True
False


Assignment Operators

Demonstrate all assignment operators

Input
#Operator +=
x = 5
x += 3

print(x)


#Operator -=
x = 5
x -= 3

print(x)


#Operator *=
x = 5
x *= 3

print(x)


#Operator /=
x = 5
x /= 3

print(x)


#Operator %=
x = 5
x%=3

print(x)


#Operator //=
x = 5
x//=3

print(x)


#Operator //=
x = 5
x//=3

print(x)


#Operrator &=
x = 5
x &= 3

print(x)


#Operator |=
x = 5
x |= 3

print(x)


#Operator ^=
x = 5
x ^= 3

print(x)


#Operator >>=
x = 5
x >>= 3

print(x)


#Operator <<=
x = 5
x <<= 3

print(x)
Output
8
2
15
1.6666666666666667
2
1
1
1
7
6
0
40


Demonstrate assignment operators on different Datatypes

Input
#assignment operators --> integer
a = 1
a += 2
print(a)

a -= 1
print(a)

a*= 10
print(a)

a %= 7
print(a)

a **= 3
print(a)

a //= 2
print(a)

a /= a
print(int(a))



#assignment operators --> float
a = 1.0
a += 2.0
print(a)

a -= 1.0
print(a)

a*= 10.0
print(a)

a %= 7.0
print(a)

a **= 3.0
print(a)

a //= 2.0
print(a)

a /= a
print(a)


#assignment operators --> string
a = "A"
a += "B"
print(a)


#assignment operators --> boolean
a = True
a += False
print(a)


#assignment operators --> lists
a = [1, 3.0, "String"]
b = [1.0, 3.0, True, False]
a += b
print(a)
Output
3
2
20
6
216
108
1
3.0
2.0
20.0
6.0
216.0
108.0
1.0
AB
1
[1, 3.0, 'String', 1.0, 3.0, True, False]


Prove if the same cross-data-type operations work with assignment or not.

#cross-data-type operations work with assignment
a = "ha"
a *= 5
print(a)
Output
hahahahaha


Assignment Operators

Demonstrate all assignment operators

Input
#Operator +=
x = 5
x += 3

print(x)


#Operator -=
x = 5
x -= 3

print(x)


#Operator *=
x = 5
x *= 3

print(x)


#Operator /=
x = 5
x /= 3

print(x)


#Operator %=
x = 5
x%=3

print(x)


#Operator //=
x = 5
x//=3

print(x)


#Operator //=
x = 5
x//=3

print(x)


#Operrator &=
x = 5
x &= 3

print(x)


#Operator |=
x = 5
x |= 3

print(x)


#Operator ^=
x = 5
x ^= 3

print(x)


#Operator >>=
x = 5
x >>= 3

print(x)


#Operator <<=
x = 5
x <<= 3

print(x)
Output
8
2
15
1.6666666666666667
2
1
1
1
7
6
0
40


Logical Operators

Show the difference between 3 != 3 and not 3 == 3

Input
#Difference between 3 != 3 and 3 == 3
a = 3 != 3
b = 3 == 3

print(a, b)
print(a and b)
Output
False True
False


Create the following statement
-> 3 is bigger than 7 or 7 is bigger than 3
-> additional type (‘5’) equals str
-> or give true out if 7 equals 3
-> The result of this one condition should be True

Input
#Logical operators statement
a = 3 > 7
b = 7 > 3
c = "5" == str
d = 7 == 3

print((a or b) or c or d)
Output
True


For- & While-Loops

Task:
-> For-loop that doubles each number beginning from 1 to 100
-> Create a while-loop that does the same
-> Save the file in the usual place

Input
# For-loop that doubles the number until the value 100
a = 1

for x in range(0, 6):
    a += a
    print(a)


# While-loop that does the same
a = 1

while a < 64:
    a += a
    print(a)
Output
2
4
8
16
32
64
2
4
8
16
32
64


Xavier Jeiziner
Xavier Jeiziner
PiBS student @Axians Amanox / FFHS