Python Programming · Week 6

Functions
In class

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

Today

Three things

  1. 1 Recap and quiz: the week 6 videos
  2. 2 Exercise 5: all three problems, solved live
  3. 3 A first look at week 7
Recap · 1

Change it once

def grade(score):

if score >= 95:

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)

report("History", 88)

←Maintenance · the A cut-off: 1 place

Math: 85 (B)

English: 72 (C)

Science: 93 (B)

History: 88 (B)

←Reuse · a new subject: 1 line

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

Recap · 2

Writing a function

def squarea name(xa parameter):colon

····4 spacesreturnthe value out x * x

a call: the name, then the argument in parentheses

print(square(4))

print(square(5))

16

25

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

Recap · 3

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

Recap · 4

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
a → 16 b → 25
41

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

Recap · 5

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'

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

Recap · 6

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

Recap · 7

return ends the function

def absolute(x): x = -3

if x < 0:

return -x

return x skipped

print(absolute(-3))

3

def absolute(x): x = 5

if x < 0:

return -x skipped

return x

print(absolute(5))

5

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

Recap · 8

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

Recap · 9

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

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

Recap · 10

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

a change inside stays inside · values go in as arguments, come out with return

Quiz

What does it print?

No computer. Say what it prints, then I run it.

1 quiz1.py

def double(x):

print(x * 2)

print(f"Result: {double(5)}")

2 quiz2.py

def total(n):

t = 0

for i in range(1, n + 1):

t += i

return t

print(total(5))

3 quiz3.py

def change():

x = 2

x = 1

change()

print(x)

Exercise 5 · Problem 1

PIN, three tries

week06_problem1.py 2 points

The PIN is 1234. Write the body of check_pin. Then ask up to three times, and check each one with check_pin. Right: Unlocked. and no more asking. Wrong: Wrong PIN. After three wrong tries: Locked.

in the file · the first line of check_pin, with its docstring

def check_pin(pin):

"""Return True if pin is the PIN, "1234", and False if not.

check_pin("1234") gives True, and check_pin("0000") gives False.

"""

# Write the body here.

your body

# Write the program here: ask for the PIN up to three times,

# and check each one with check_pin.

your program

Hint: input gives a string, so compare with "1234".

on the screen · one run

PIN: 0000

Wrong PIN.

PIN: 1234

Unlocked.

the values after the prompts are typed · the prompt words are up to you

examples · typed values in order

typed

prints

1234

Unlocked.

0000, 1234

Wrong PIN. then Unlocked.

1111, 2222, 1234

Wrong PIN. twice, then Unlocked.

1111, 2222, 3333

Wrong PIN. three times, then Locked.

Exercise 5 · Problem 2

Goldbach: two primes

week06_problem2.py 3 points

Every even number from 4 up is the sum of two primes (Goldbach's conjecture, never proved). Ask for n. Not an even number from 4 up (check with is_even): say so. Otherwise try p = 2, 3, 4, … in order, print the first way you find, and stop.

in the file · is_even and is_prime from examples 1 and 3, as you typed them

def is_even(n):

return n % 2 == 0

def is_prime(n):

count = 0

for d in range(1, n + 1):

if n % d == 0:

count += 1

return count == 2

# Write your program here, using is_even and is_prime.

your program

Hint: if p is prime and n - p is prime too, then n = p + (n − p).

on the screen · one run

n: 28

28 = 5 + 23

the value after the prompt is typed · the prompt word is up to you

examples · typed values in order

typed

prints

4

4 = 2 + 2

28

28 = 5 + 23

1000

1000 = 3 + 997

7

Not an even number from 4 up.

2

Not an even number from 4 up.

Exercise 5 · Problem 3

Counting in binary

week06_problem3.py 5 points

Write the body of to_binary(n): it returns the binary digits of n as a string. 11 is 8 + 2 + 1, so to_binary(11) gives "1011". The program in the file prints 1 to n in binary with it.

in the file · the first line of to_binary, and the program

def to_binary(n):

"""Return the binary digits of n, a positive integer, as a string.

to_binary(11) gives "1011", and to_binary(8) gives "1000".

"""

# Write the body here.

your body

n = int(input("n: "))

for k in range(1, n + 1):

print(f"{k}: {to_binary(k)}")

  1. 1 Divide n by 2 again and again: each remainder, n % 2, is the next digit from the right; n // 2 is what is left.
  2. 2 Put each new digit, as a string, in front of the digits you have.
  3. 3 When nothing is left to divide, return the digits.

on the screen · one run

n: 5

1: 1

2: 10

3: 11

4: 100

5: 101

the value after the prompt is typed · the program is given

examples · typed values in order

typed

prints

1

1: 1

4

1: 1 … 4: 100

11

1: 1 … 11: 1011

16

1: 1 … 16: 10000

Next week

Week 7: Lists and Tuples

Videos and exercise 6: up Tuesday–Wednesday.
Exercise 6: due Monday, October 19, 11:59 a.m.
Midterm: Monday, October 26, 8:00–8:50 a.m.

Slides: hyeongminlee.github.io/slides/python-programming

← All weeks
01 / 00
Scroll · ↓ · Space