items = []
while True:
n = int(input("Enter a number: "))
if n==0:
break
items.append(n)Notes S-10/Python 7: Loop control, functions, and dictionaries
TODO: Additional exercise (Insurance) - PR shares it
Notes:
- Functions: at least one problem set in the exam.
- Dictionaries: less relevant for the exam (do not explicitly announce as not relevant at the beginning) - maybe as multiple-choice.
Cover loop termination, functions, and dictionaries, while retaining the planned exercise order and exam guidance.
Slide 115 — break and continue
break terminates the loop, whereas continue skips the rest of the current iteration.
for val in "string":
if val == "i":
break
print(val)
print("The end")for val in "string":
if val == "i":
continue
print(val)
print("The end")Slide 116 — Loop termination
- Extend the code to end the loop when the user enters 0.
In-class exercise ../materials/session_10/StopLoop.py
- Expand the dice game again.
Assign exercise 2 as homework.
Homework ../materials/session_10/dicegame3.py
import random
stake = int(input('How much money would you like to invest? '))
continue_ = True
while continue_:
pasch = False
try_ = 1
while pasch==False and try_<4:
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
print("The throw brought", dice1, "and", dice2)
if dice1==dice2:
pasch = True
break
try_ = try_ + 1
if pasch==True:
print("You have won!!! It's a double", dice1)
payout = stake * dice1
print("You get", payout, "Euro!")
continue_ = bool(int(input('Would you like to continue? 1=yes, 0=no: ')))
if continue_:
stake = payout
else:
print("Unfortunately you have lost!!!")
continue_ = FalseAn additional insurance exercise is shared by PR. TODO: Add its mapping when the material is available.
Slide 118 — Defining functions
Parameters receive call arguments, return sends a value to the caller, and a function call runs the reusable body.
def square(x):
sq = x * x
return sq
x = 2
y = square(x)
print(x, y)def add(x, y):
return x + y
x = 2
y = 3
z = add(x, y)
print(x, y, z)def fibonacci(n):
fib = [0, 1]
for i in range(n):
fib.append(fib[-2] + fib[-1])
return fib
n = int(input("How many numbers: "))
print(fibonacci(n))Slide 120 — Reusing functions
One function can call another, and defining reusable functions reduces duplication.
def square(x):
sq = x * x
return sq
def sumofSquares(numberlist):
sum_ = 0
for i in numberlist:
squaredValue = square(i)
sum_ += squaredValue
return sum_
a = 2
b = 3
c2 = square(a) + square(b)
print(c2)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
total = sumofSquares(numbers)
print("Sum of the Square of List of Numbers:", total)Slides 121–122 — Functions
Order, in-session: 4, 5, 1, 6 (if time permits). Assign 2,3 as homework.
- Write a function count_digits(int)
In-class exercise ../materials/session_10/CountDigits.py
def count_digitsa(number):
snum = str(number)
count = len(snum)
return count
def count_digitsb(number):
count = 0
while number>0:
number = number//10
count = count + 1
return count
number = int(input("Please enter a number: "))
print("The number of Digits is", count_digitsa(number))
print("The number of Digits is", count_digitsb(number))- Write a Python function to multiply all the numbers in a list.
Homework ../materials/session_10/Listmult.py
def multi(x):
n = len(x)
prodX = 1.0
for i in range(n):
prodX = prodX * x[i]
return prodX
li = [8, 2, 3, -1, 7, 5, 6 ]
print ("Product =", multi(li))- Write a function isHarshad(int)
Homework ../materials/session_10/Harshad.py
def isHarshad(num):
num_string = str(num)
num_sum = 0
for i in range(len(num_string)):
num_sum = num_sum + int(num_string[i])
if (num%num_sum==0):
return True
else:
return False
number = int(input("Please enter a number: "))
print(isHarshad(number))- Write a Python function to calculate the factorial of a number (n!).
In-class exercise ../materials/session_10/Factorial.py
def factorial(n):
fac = 1
for i in range(1, n+1):
fac = fac * i
return fac
n = int(input("Enter a number: "))
print ("Factorial =", factorial(n))- Extend the program by adding a function which calculates the number of possible combinations
In-class exercise ../materials/session_10/Combinations.py
def factorial(n):
fac = 1
for i in range(1, n+1):
fac = fac * i
return fac
def combinations(n,k):
return (factorial(n)/(factorial(n-k)*factorial(k)))
n = int(input("Enter n: "))
k = int(input("Enter k: "))
print ("Combinations =", combinations(n,k))- Write a program that simulates a slotmachine
In-class exercise ../materials/session_10/SlotMachine.py
# Version 1: Simply 3 random numbers
import random
def run_Slotmachine():
result = [0, 0, 0]
for i in range(3):
result[i] = random.randint(1,6)
return result
result = run_Slotmachine()
if result[0]==result[1]==result[2]:
print("You have won: ", result)
else:
print("You have lost: ", result)
# Version 2: 3 random numbers generated by 100 Iterations
import random
def run_Slotmachine():
result = [0, 0, 0]
for i in range(3):
for j in range(100):
result[i] = random.randint(1,6)
return result
result = run_Slotmachine()
if result[0]==result[1]==result[2]:
print("You have won: ", result)
else:
print("You have lost: ", result)
# Version 3: 3 random numbers generated by random Iterations
import random
def run_Slotmachine():
result = [0, 0, 0]
for i in range(3):
for j in range(random.randint(1,100)):
result[i] = random.randint(1,6)
return result
result = run_Slotmachine()
if result[0]==result[1]==result[2]:
print("You have won: ", result)
else:
print("You have lost: ", result)
# Version 4: 3 random numbers generated by random Iterations
import random
def run_Slotmachine():
result = [0, 0, 0]
for i in range(3):
for j in range(random.randint(1,100)):
result[i] = random.randint(1,6)
return result
result = run_Slotmachine()
if result[0]==result[1]==result[2]:
print("You have won: ", result)
else:
print("You have lost: ", result)
import random
def run_Slotmachine():
result = [0, 0, 0]
for i in range(3):
for j in range(100):
result[i] = random.randint(1,6)
return result
result = run_Slotmachine()
if result[0]==result[1]==result[2]:
print("You have won: ", result)
else:
print("You have lost: ", result)At least one exam exercise will cover functions.
Slide 125 — Using an external module
The module name acts as a namespace prefix.
import math
print(math.sin(5))
print(math.sin(math.pi))Slide 127 — Creating a dictionary
Dictionaries use curly braces to associate unique keys with values.
dict1 = {
'Peter': 55,
'Mary': 40,
'Bob': 34,
}
dict1Slide 128 — Accessing and modifying dictionaries
The second and third expressions below intentionally raise KeyError because those keys do not exist.
dict1['Mary']
dict1['Hans']
dict1[0]a = 'Peter'
dict1[a]dict1['Alice'] = 55
dict1dict1['Mary'] = 41
dict1stockprices = {
'Date': [
'1.1.2021',
'2.1.2021',
'1.1.2021',
'2.1.2021',
],
'BMW': [89, 91, 95, 92],
'Telekom': [12, 10, 14, 17],
'SAP': [114, 119, 125, 130],
}These examples demonstrate lookup, insertion, replacement, and list values.
Slide 129 — Complex and nested dictionaries
Values can themselves be dictionaries or lists, and keys may be strings or numbers.
contacts = {
'name': 'Alice',
'age': 30,
'address': {
'street': '123 Main St',
'city': 'Wonderland',
'zip': '12345',
},
'phone_numbers': [
{
'type': 'home',
'number': '123-456-7890',
},
{
'type': 'work',
'number': '987-654-3210',
},
],
}product_details = {
'product_id': 101,
'name': 'Laptop',
'price': 799.99,
'in_stock': True,
'tags': ['electronics', 'computer'],
}item_quantities = {
1: 50,
2: 30,
3: 75,
}students = {
'student1': {
'name': 'John',
'age': 22,
'courses': ['Math', 'Science'],
},
'student2': {
'name': 'Jane',
'age': 24,
'courses': ['History', 'Literature'],
},
}Slide 130 — Accessing nested dictionary values
Use successive keys to access nested values; a list stored inside a dictionary can be modified with its list methods.
students['student1']
students['student1']['age']
students['student1']['courses']
students['student1']['courses'][0]students['student1']['haircolor'] = 'blonde'
students['student1']['courses'].append('Informatics')
students['student1']Slide 131 — Adding, changing, and deleting nested data
students['student3'] = {
'name': 'Peter',
'age': 25,
'courses': ['Finance'],
}
students['student3']['weight'] = 23del students['student3']['weight']
del students['student3']students['student2']['courses'].append('Informatics')
students['student1']['courses'].remove('Math')
students['student1'] = {'age': 25}The final assignment replaces the complete student1 dictionary rather than changing only its age.
Slide 132 — Save and load dictionaries with JSON
Write mode creates or replaces the file and json.dump() serializes the dictionary; read mode opens it and json.load() reconstructs the data.
import json
with open('students.db', 'w', encoding='utf-8') as file:
json.dump(students, file)
with open('students.db', 'r', encoding='utf-8') as file:
students = json.load(file)☕ Break — 10 minutes
Slide 133 — Dictionaries and persistence
In-class exercise ../materials/session_10/Friends.py
friends = {'friend1' : {'name':'Peter', 'likes':['biking', 'techno'], 'food_intolerances':['pepper', 'cucumber']},
'friend2' : {'name':'Maria', 'likes':['dancing', 'skiing'], 'food_intolerances':['nuts']}}
import json
file = open('friends.db', 'w')
json.dump(friends, file)
# Remove all variables from kernel namespace
import json
file = open('friends.db', 'r')
friends = json.load(file)
friends
friends['friend1']
friends['friend1']['name']
friends['friend2']['likes']
friends['friend3'] = {'name':'Jane', 'age':22, 'likes':['hiking', 'dancing'], 'food_intolerances':['gluten', 'milk']}
friends['friend1']['likes'].append('reading')
del friends['friend3']['age']
del friends['friend1']
file = open('friends.db', 'w')
json.dump(friends, file)- Dictionaries are less relevant to the exam; do not announce this explicitly at the beginning. They may appear in a multiple-choice question.
friends.db is preserved in the exercise table, but it is not supplied as input material. Friends.py generates it at runtime.
Summary and announcements
- TODO
Take notes on improvements and common questions during the session and add them to feedback.qmd afterwards.