Lecture 5
Lecture 5
Programming
Steve James
Lecture 5
Homework
• Write a program that reads a series of names
into a list. Use your own name and your
friends’! Loop through each name in the list
and flip a coin. If heads, the person survives. If
tails, the person does not!
• Print out all the people that survived Thanos’
plan! Did you?
import random
names = list()
name = input()
while name != "":
names.append(name)
name = input()
for name in names:
if random.choice([True, False]):
print(name, "survived")
else:
print(name, "dead")
RECAP
LISTS
Lists
• A list is a built-in type that lets us store a
collection of values
values = [27, 39, False, "Batman > Superman"]
• Loop through:
for x in values:
print(x)
• Check if contains
if 28 in values:
Python
ASSOCIATIVE CONTAINERS
Associative arrays
• Collections of key-value pairs
• Also known as maps, dictionaries, symbol
tables
• Offer ability to:
– add a key-value pair to the collection
– remove a key-value pair
– modify an existing pair
– lookup a value given a particular key
• In Python, we use a dictionary (dict)
Example
• Students have names and marks
• Want to relate mark to each name
– i.e. given a name, what is the mark?
Vegeta: 99
Goku: 9001
Freeza: 80
dict
• Create an empty dict using:
my_dict = dict() # or my_dict = {}
marks = dict()
marks["Vegeta"] = 99
marks["Goku"] = 9001
marks["Vegeta"] = 40 # overwrites
Removing
marks = dict()
marks["Vegeta"] = 99
marks["Goku"] = 9001
marks["Vegeta"] = 40
marks.pop("Vegeta")
Querying
marks = dict()
marks["Vegeta"] = 99
marks["Goku"] = 9001
is_goku_a_key = "Goku" in marks
goku_mark = marks["Goku"]
Iteration
marks = dict()
marks["Vegeta"] = 99
marks["Goku"] = 9001
for name, mark in marks.items():
print(name, ":", mark)
"""
Output:
Vegeta : 99
Goku : 9001
"""
set
• Stores keys only, not key-value pairs
• Keys are unique
• Keys are not ordered!
• KEYS CANNOT BE OVERWRITTEN ONCE INSERTED
• Create an empty set using:
my_set = set()
FUNCTIONS
Example
• Calculate the bill for a table at a restaurant
– Restaurant has multiple tables
– Consider
• Discount
• Tax
• Tip
Without function
# Table 1 Bill Calculation (in Rands) tip_table2 = subtotal_table2 * 0.15
items_table1 = [85.50, 65.00, 105.75] # Prices of items in final_total_table2 = subtotal_table2 + tax_table2 +
Rands tip_table2
total_table1 = sum(items_table1)
if total_table1 > 200: print("Table 2 Bill:")
discount_table1 = total_table1 * 0.10 # 10% discount print("Items:", items_table2)
if total > R200 print("Total: R", total_table2)
else: print("Discount: R", discount_table2)
discount_table1 = 0 print("Subtotal after discount: R", subtotal_table2)
subtotal_table1 = total_table1 - discount_table1 print("Tax (15%): R", tax_table2)
tax_table1 = subtotal_table1 * 0.15 # 15% VAT print("Tip (15%): R", tip_table2)
tip_table1 = subtotal_table1 * 0.15 # 15% tip print("Final Total: R", final_total_table2)
final_total_table1 = subtotal_table1 + tax_table1 + print()
tip_table1
# Table 3 Bill Calculation (in Rands)
print("Table 1 Bill:") items_table3 = [50.00, 50.00, 50.00, 50.00, 50.00]
print("Items:", items_table1) total_table3 = sum(items_table3)
print("Total: R", total_table1) if total_table3 > 200:
print("Discount: R", discount_table1) discount_table3 = total_table3 * 0.10
print("Subtotal after discount: R", subtotal_table1) else:
print("Tax (15%): R", tax_table1) discount_table3 = 0
print("Tip (15%): R", tip_table1) subtotal_table3 = total_table3 - discount_table3
print("Final Total: R", final_total_table1) tax_table3 = subtotal_table3 * 0.15
print() tip_table3 = subtotal_table3 * 0.15
final_total_table3 = subtotal_table3 + tax_table3 +
# Table 2 Bill Calculation (in Rands) tip_table3
items_table2 = [150.00, 120.00, 90.00, 60.00]
total_table2 = sum(items_table2) print("Table 3 Bill:")
if total_table2 > 200: print("Items:", items_table3)
discount_table2 = total_table2 * 0.10 print("Total: R", total_table3)
else: print("Discount: R", discount_table3)
discount_table2 = 0 print("Subtotal after discount: R", subtotal_table3)
subtotal_table2 = total_table2 - discount_table2 print("Tax (15%): R", tax_table3)
tax_table2 = subtotal_table2 * 0.15 print("Tip (15%): R", tip_table3)
What’s the problem?
• Monolithic code
– Hard to read
– Impossible to maintain
• No code reuse
– We write something that other users may be
interested in. Want to make that available
# Call the function for each table with different lists of item prices
print_bill(1, [85.50, 65.00, 105.75])
print_bill(2, [150.00, 120.00, 90.00, 60.00])
print_bill(3, [50.00, 50.00, 50.00, 50.00, 50.00])
What are functions?
• Also called methods, procedures, subroutines
• A function is a piece of code or a module that
– Has been “packaged” as a unit
– Usually serve a single purpose / task
– Performs a task and then returns control to the caller
• After the function has performed the task, the program will
continue execution from the point after the call
– Can be executed several times and called from
different places during a single execution of a program
What are functions?
• Consider mathematical functions:
Let 𝑓 𝑥 = 𝑥 2
• 𝑥 is the parameter
𝑓 𝑡 = 𝑡2
2 𝑓 𝑥 =
𝑓 𝑥 =𝑥
𝑥2
𝑠𝑞𝑢𝑎𝑟𝑒 𝑛𝑢𝑚 :
𝑛𝑢𝑚2
Some function
0 or more things
0 or more inputs
returned
def <function_name>(<parameter_list>):
<function_body>
Examples
How to call the functions:
def greet():
print("Hello!") greet()
"""
Traceback (most recent call last):
File "main.py", line 5, in <module>
show_message(m, n)
NameError: name 'show_message' is not defined
"""
Function Return
• Functions can return in 3 ways
– Executing all the statements in the function body
(for void functions)
– Running into the statement return (for void
functions)
– Running into the statement return <exp>;
• non- void functions must return like this
Examples
# we run into the end of the function and exit
def f():
print("Hello, world!")
# returns here
if y == 0:
print("y can't be 0")
return # returns here
print("Calculating...")
z = (x * x + y * y) / y;
print("The answer is", z)
• Good practice:
– Functions should only return one logical thing