Python Programming · Week 6
Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering
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?
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
>>> 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.520also printinputfloatstrtyperange
a function: values go in, a value comes out · a call: the name, then the arguments in parentheses
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 square(x):
return x * x
a = square(4)
b = square(5)
print(a + b)
the def line stores the function
a parameter: any name
def square(n):
return n * n
41
a call: into the body with the argument · back to the call with the return value
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
def power(base, exponent):
return base ** exponent
print(power(2, 3))
print(power(3, 2))
print(power(2))
TypeError: power() missing 1 required positional argument: 'exponent'
one argument short
first argument → first parameter · positional arguments: the order matters
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
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
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
16
Score: 85
85
----------
Hello!
a function may take nothing, or give back nothing · the parentheses stay
def square(x):
print(x * x)
a = square(4)
print(a)
print(a + 1)
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)
16
17
print shows it on the screen · return gives it back to the call
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
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
an argument goes by position, or by name · keyword arguments: any order
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
global variables · outside every function
local variables: only inside the function · only during the call
def add_bonus(score):
score = score + 5
score = 80
add_bonus(score)
print(score)
global
local · add_bonus
def add_bonus(score):
return score + 5
score = 80
score = add_bonus(score)
print(score)
global
local · add_bonus
return it, then store it
two variables named score · a change inside stays inside
parameters and variables made in a function: local · they exist only during the call
the same name outside: a different variable
values go in as arguments · they come out with return
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
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)
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
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
Have Python open. Type everything with me.
See you in class.