hanegreefs.com/Business Information SystemsBIS
Python 4 · unit 7 of 16

Functions and files

Defining and calling functions, print versus return, default parameters, local variables and side effects, the investment example, and reading and writing text files.

Based on: lecture 4 (functions in Python), exercise sessions WPO5 (functions) and WPO6 (reading and writing files) · About 65 minutes

Definition and callImportant

A function is a named block of code. The definition starts with def, the name and the formal parameters; the body is indented. Nothing happens until the function is called with actual parameters (arguments).

def power(base, exponent):    # definition with formal parameters
    answer = base ** exponent
    return answer

n = int(input("Base: "))
e = int(input("Exponent: "))
print(n, "to the power", e, "=", power(n, e))   # call with actual parameters

The four golden rules of the programming lecture apply: same name in definition and call, the same number of parameters, matching types, and return when the function must deliver a value.

Print versus returnImportant

This is the most tested distinction of the Python part. print shows something on the screen and the function then gives back None. return hands a value back to the caller, who can store it, compute with it or print it, and it ends the function immediately.

VersionCodeWhat print(f(5, 2)) shows
Procedure style (prints)def f(x, y): print(x ** y)25 and then None
Function style (returns)def f(x, y): return x ** y25
Common trapExam programs often contain print(greet("Emma")) where greet itself prints and has no return: the output is the greeting followed by None. And a call like add(1) on its own line computes a value and throws it away.

Default parameters, scope and side effectsImportant

A parameter can get a default value: def with_vat(price, rate=0.21). Calling with_vat(100) uses 21%, with_vat(100, 0.06) uses 6%. Parameters with a default must come after those without.

Variables created inside a function are local: they exist only during the call. Printing a parameter name outside its function gives a NameError. The function can read variables of the main program, but should get what it needs through its parameters.

Numbers and strings passed to a function behave like pass by value: assigning a new value inside the function does not change the caller's variable. A list or dictionary passed to a function is the same object, so items.append(x) or items[0] = 9 inside the function changes the caller's list: a side effect, like pass by reference. To avoid it, build and return a new list.

def discounted(prices, pct):
    return [round(p * (1 - pct / 100), 2) for p in prices]

old = [10.0, 20.0]
new = discounted(old, 10)
print(old, new)     # [10.0, 20.0] [9.0, 18.0]

The investment exampleImportant

The lecture uses compound interest to practise functions: the capital after n years is Kn = K0 × (1 + i)n. A function prints the balance for every year.

def investment(start, years, rate):
    for year in range(1, years + 1):
        balance = round(start * (1 + rate) ** year, 2)
        print("year", year, "=", balance, "EUR")

investment(1000, 4, 0.1)
Worked example

1000 euro at 10% for 4 years

Follow the loop of the function.

1

Year 1

1000 × 1.1 = 1100.0
2

Year 2

1000 × 1.12 = 1210.0
3

Year 3

1000 × 1.13 = 1331.0
4

Year 4

1000 × 1.14 = 1464.1
Answer

The function prints four lines, ending with year 4 = 1464.1 EUR. A second function can loop over a list of interest rates and call investment for each one: a function that calls another function. Try other numbers in the investment lab.

Reading and writing filesImportant

A file keeps data after the program ends. open(name, mode) opens it: "r" reads (the default), "w" writes and empties the file first, "a" appends at the end. Use with so the file is closed automatically.

with open("stock.txt", "w") as f:
    f.write("pen;120\n")
    f.write("paper;40\n")

total = 0
with open("stock.txt") as f:
    for line in f:
        name, qty = line.strip().split(";")
        total += int(qty)
print(total)    # 160
MethodGives
f.read()the whole file as one string
f.readline()the next line, including its \n
f.readlines()a list of all lines
for line in fthe lines one by one (the usual way)
f.write(text)writes text; add \n yourself for a new line
Common trapEvery line read from a file ends with \n, and everything read is a string. Use strip() before comparing or splitting, and int() or float() before calculating. Opening a file that does not exist for reading gives a FileNotFoundError.

Key takeaways

  • def defines, a call runs; formal parameters versus actual parameters.
  • print shows, return gives back; a function without return gives None.
  • Local variables disappear after the call; lists passed in can be changed (side effect).
  • Kn = K0 × (1 + i)n is the investment example.
  • Open files with with; "w" empties the file; lines are strings ending in \n.

Loading cards
Question
Click, tap or press space to flip
Answer

Multiple choice (8)

Question 1 · Python 4

def f(x): print(x * 2). What does print(f(3)) show?

Why: f prints 6 and returns None, which is then printed.
Question 2 · Python 4

def add(a, b=10): return a + b. What is add(5)?

Why: b takes its default 10.
Question 3 · Python 4

def f(n): n = n + 1. x = 5; f(x); print(x)

Why: Reassigning the parameter does not change the caller's number.
Question 4 · Python 4

def f(lst): lst.append(1). a = []; f(a); f(a); print(a)

Why: The list is shared and changed twice.
Question 5 · Python 4

Which statement ends a function immediately and hands back a value?

Why: return.
Question 6 · Python 4

A file stock.txt holds three lines. What does len(open("stock.txt").readlines()) give?

Why: readlines gives a list with one string per line.
Question 7 · Python 4

What happens to the existing content when you open a file with "w"?

Why: Mode w truncates the file.
Question 8 · Python 4

def investment(amount, years, interest) is called as investment(1000, 0.1, 4). What is wrong?

Why: Golden rule: matching parameters in number, order and type.

Exam-style open questions (2)

Open question · Python 4

Function with return

Rewrite the grade program as a function gradeConverter(mark) that returns the letter, and show how you call it and print the result for a mark read from the keyboard.

Show a model answer outline
  • def gradeConverter(mark): if, elif chain, return the letter.
  • mark = int(input(...)).
  • print("The grade =", gradeConverter(mark)).
  • Explain why return is better than print here (reuse, testing).
Open question · Python 4

Total from a file

A file sales.txt holds one line per sale in the form product;amount. Write a program that prints the total amount. Name two pitfalls.

Show a model answer outline
  • with open("sales.txt") as f, loop over lines.
  • strip, split(";"), float(amount), add to total.
  • Pitfalls: the \n at the end, and strings that must be converted before adding.
  • Optional: skip empty lines.

LabCoding lab: functions and files

Files you read or write here live in a temporary memory of the sandbox and disappear after each run.

LabInvestment calculator

Enter the amount, the number of years and the interest rate as a decimal or a percentage. The table shows the balance after each year.