Python Programming · Week 6

Functions

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

This week

The same lines, three times

score = 85

if score >= 9095:

print(f"Math: {score} (A)")

elif score >= 80:

print(f"Math: {score} (B)")

else:

print(f"Math: {score} (C)")

score = 72

if score >= 9095:

print(f"English: {score} (A)")

elif score >= 80:

print(f"English: {score} (B)")

else:

print(f"English: {score} (C)")

score = 93

if score >= 90:missed

print(f"Science: {score} (A)")

elif score >= 80:

print(f"Science: {score} (B)")

else:

print(f"Science: {score} (C)")

Math: 85 (B)

English: 72 (C)

Science: 93 (A) ← should be B

the same 7 lines × 3

only the score and the subject differ

raise the A cut-off to 95

3 places to change · one missed: Science gets A, not B

more subjects later

each one: 7 more lines · 10 subjects: 70 lines

copied lines · write them once instead?

This week

Write it once

def grade(score):

if score >= 90:

return "A"

elif score >= 80:

return "B"

else:

return "C"

def report(subject, score):

print(f"{subject}: {score} ({grade(score)})")

report("Math", 85)

report("English", 72)

report("Science", 93)

←written once

←raise the A cut-off to 95? 1 place

Maintenance

change one place · every subject follows

Reuse

write once, use many times · a new subject: 1 line

←1 line per subject, not 7

Math: 85 (B)

English: 72 (C)

Science: 93 (A)

the same output

lines with a name: a function · easy to maintain, easy to reuse

Functions

Functions you already know

>>> len("Python")

6

>>> abs(-3.5)

3.5

>>> int("20")

20

argumentgoes in

"Python"-3.5"20" ↓↓↓

functiondoes the work

lenabsint ↓↓↓

return valuecomes out

63.520

also printinputfloatstrtyperange

a function: values go in, a value comes out · a call: the name, then the arguments in parentheses

def

Your own function

def square(x):

return x * x

print(square(4))

print(square(5))

←def, a name, a parameter, :

←the body · return: the value out

←calls: an argument in

 

only the def: no output

16

25

each call: x takes the argument

def: define a function · the body runs only when it is called

def

Into the body and back

def square(x):

return x * x

a = square(4)

b = square(5)

print(a + b)

call x = 4
back with 16
call x = 5
back with 25
comes back here 4 * 4 = 16

the def line stores the function

a → 16 b → 25

a parameter: any name

def square(n):

return n * n

the body of square x = 4 16 x = 5 25 a = square(4) b = square(5) print(a + b) return x * x

41

a call: into the body with the argument · back to the call with the return value

def

def first, then the call

print(square(4))

def square(x):

return x * x

NameError: name 'square' is not defined

at the call, square does not exist yet

def square(x):

return x * x

print(square(4))

16

Python runs from the top · define first, then call

Parameters

Matched by position

def power(base, exponent):

return base ** exponent

print(power(2, 3))

print(power(3, 2))

print(power(2))

def power( power(power(power(
1st base ↑ 232
, ,,
2nd exponent ↑ 32
): )))
2 ** 3 → 8 3 ** 2 → 9 TypeError

TypeError: power() missing 1 required positional argument: 'exponent'

one argument short

first argument → first parameter · positional arguments: the order matters

return

The call becomes its value

def square(x):

return x * x

y = square(4)

print(y)

print(square(3) + 1)

16

10

y = square(4)

→y = 16

print(square(3) + 1)

→print(9 + 1)

→print(10)

the call becomes the returned value · store it, add to it, print it

return

return ends the function

def absolute(x): x = -3x = 5

if x < 0:

return -x skipped

return x skipped

print(absolute(-3))

print(absolute(5))

3

5

absolute(-3): -3 < 0 is True → return 3

absolute(5): False → the last line, return 5

return: the function ends at once · the lines below it are skipped

return

A call inside a call

def square(x):

return x * x

def sum_of_squares(a, b):

return square(a) + square(b)

print(sum_of_squares(3, 4))

25

print(sum_of_squares(3, 4))

→print(square(3) + square(4))

a = 3, b = 4

→print(9 + 16)

square(3) → 9 · square(4) → 16

→print(25)

9 + 16 → 25

the inner calls first · each call waits for its value

Variations

Parameters and return are optional

return
no return
parameter
no parameter

def square(x):

return x * x

print(square(4))

16

def get_score():

return int(input("Score: "))

print(get_score())

Score: 85

85

def draw_line(n):

print("-" * n)

draw_line(10)

----------

def greet():

print("Hello!")

greet()

Hello!

a function may take nothing, or give back nothing · the parentheses stay

return

print or return?

def square(x):

print(x * x)

a = square(4)

print(a)

print(a + 1)

to the screen a → None

16

None

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

def square(x):

return x * x

b = square(4)

print(b)

print(b + 1)

back with 16 b → 16

16

17

print shows it on the screen · return gives it back to the call

Parameters

Default values

def power(base, exponent=2):

return base ** exponent

print(power(5, 3))

print(power(5))

←default value

→125 exponent = 3

→25 exponent = 2

given: it replaces the default

left out: the default value

a default value · an argument you may leave out

Parameters

Keyword arguments

def power(base, exponent=2):

return base ** exponent

print(power(5, 3))

print(power(base=5, exponent=3))

print(power(exponent=3, base=5))

print(power(5, exponent=3))

→125 by position

→125 by name

→125 by name, any order

→125 by position, then by name

print(power(base=5, 3)) → SyntaxError: positional argument follows keyword argument
print("Hi", end=" ") a keyword argument · end: a parameter of print, default value: a new line

an argument goes by position, or by name · keyword arguments: any order

Local variables

Inside stays inside

def get_area(width, height):

area = width * height

return area

result = get_area(3, 5)

print(result)

print(area)

15

NameError: name 'area' is not defined

local variables · get_area, during the call

width3 height5 area15
gone after the call

global variables · outside every function

result15

local variables: only inside the function · only during the call

Local variables

Two variables, one name

def add_bonus(score):

score = score + 5

score = 80

add_bonus(score)

print(score)

80

global

score80
print(score) reads this
80 ⟶

local · add_bonus

score80 → 85
gone after the call

def add_bonus(score):

return score + 5

score = 80

score = add_bonus(score)

print(score)

85

global

score80 → 85
80 ⟶ ⟵ 85

local · add_bonus

score80 → 85
gone after the call

return it, then store it

two variables named score · a change inside stays inside

Local variables

Local variables

1

parameters and variables made in a function: local · they exist only during the call

2

the same name outside: a different variable

3

values go in as arguments · they come out with return

This week

The whole program

def grade(score):

if score >= 90:

return "A"

elif score >= 80:

return "B"

else:

return "C"

def report(subject, score):

print(f"{subject}: {score} ({grade(score)})")

report("Math", 85)

report("English", 72)

report("Science", 93)

←grade: a score in, a letter out

←a return in each branch

←report: two parameters

←calls grade, prints · no return

←three calls, one line each

written once · called three times

This week

Which lines run in each call

def grade(score):

if score >= 90:

return "A"

elif score >= 80:

return "B"

else:

return "C"

def report(subject, score):

print(f"{subject}: {score} ({grade(score)})")

report("Math", 85)

report("English", 72)

report("Science", 93)

score = 85 "B"
score = 72 "C"
score = 93 "A"

the two def lines run once, at the start: the two functions are stored

report("Math", 85)

calls grade(85)→ returns "B"

prints Math: 85 (B)

report("English", 72)

calls grade(72)→ returns "C"

prints English: 72 (C)

report("Science", 93)

calls grade(93)→ returns "A"

prints Science: 93 (A)

each call: a new subject and score
grade runs inside report

Tips

Naming a function

a name that says what it does

gradereportis_evendraw_triangle

avoid fdo_itfunc1

lowercase, words joined by _, like variables

def grade(score):

"""Return the letter grade for a score."""

if score >= 90:

⋮

a docstring: what the function does

VS Code shows it when you point at the name

Next steps

Next: the practice video.

Have Python open. Type everything with me.

See you in class.

← All weeks
01 / 00
Scroll · ↓ · Space