Python Programming · Week 6

Functions
Practice

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

Setup

Before we start

A new folder for this week.

  1. 1 VS Code → open your python_course folder
  2. 2 New Folder → week06

This video is all typing. Pause whenever you need to catch up.

Files

report.py

In your week06 folder: the program from the theory video.

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)

Math: 85 (B)

English: 72 (C)

Science: 93 (A)

grade: a score in, a letter out

report: prints one line, using grade

Debugger

Step into a call inside a call

1def grade(score):

2 if score >= 90:

3 return "A"

4 elif score >= 80:

5 return "B"

6 else:

7 return "C"

8

9def report(subject, score):

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

11

12report("Math", 85)

13report("English", 72)

14report("Science", 93)

what the debugger shows inside grade

Locals

score 85

CALL STACK

grade

report

<module>

  1. 1 click just left of line 12's number: a breakpoint
  2. 2 the small arrow next to ▷ → Python Debugger: Debug Python File
  3. 3 Step Into (F11): into report · Locals: subject, score
  4. 4 Step Into again: into grade · CALL STACK: grade above report
  5. 5 Step Over (F10) past return "B": back in report
  6. 6 Step Over: Math: 85 (B) is printed · back in the main program
  7. 7 ■ Stop
  8. Mac: F10 and F11 may need fn · or click the icons (Step Into: an arrow down to a dot)

report waits while grade runs · the call stack: the calls still waiting

Drill

Break three things

In report.py, on purpose. After each one, undo it: ⌘Z (Windows: Ctrl+Z).

report.py, lines 1-7

cut grade (⌘X) · paste it below the calls

NameError: name 'grade' is not defined

grade is called before its def has run

report.py, line 7

change return "C" to print("C")

Math: 85 (B)

C

English: 72 (None)

Science: 93 (A)

print is not return: the call gives back None

report.py, line 12

delete 85: report("Math")

TypeError: report() missing 1 required positional argument: 'score'

one argument short

an error: read its last line · None where a value should be: a missing return

Files

Change it once

Two changes in report.py: raise the A cut-off to 95, and add a subject.

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)

Math: 85 (B)

English: 72 (C)

Science: 93 (B)

History: 88 (B)

Maintenance · the A cut-off: 1 place

Reuse · a new subject: 1 line

Example · 1

Even numbers

even.py

Write is_even(n): True if n is even, False if not. Use it to print the even numbers from 1 to 10 on one line.

a function that returns True or False · its call can be the condition of an if

on the screen

2 4 6 8 10

the code

def is_even(n):
    return n % 2 == 0

for i in range(1, 11):
    if is_even(i):
        print(i, end=" ")
print()
Example · 2

Factorial

factorial.py

Write the body of factorial(n): it returns n! = 1 × 2 × … × n. The program in the file prints 1! up to n! with it.

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

def factorial(n):

"""Return n factorial: 1 x 2 x ... x n.

factorial(5) gives 120.

"""

# Write the body here.

your body

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

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

print(f"{k}! = {factorial(k)}")

on the screen · one run

n: 5

1! = 1

2! = 2

3! = 6

4! = 24

5! = 120

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

examples · typed values in order

typed

prints

1

1! = 1

5

1! = 1 … 5! = 120

10

1! = 1 … 10! = 3628800

Example · 2

Factorial: the body

factorial.py

the file, with the body written

def factorial(n):

"""Return n factorial: 1 x 2 x ... x n.

factorial(5) gives 120.

"""

result = 1

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

result *= i

return result

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

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

print(f"{k}! = {factorial(k)}")

on the screen · one run

n: 5

1! = 1

2! = 2

3! = 6

4! = 24

5! = 120

the lit lines are the body · the rest was in the file

Example · 3

Primes up to n

primes.py

Turn last week's prime check into a function, is_prime(n). Ask for a number and print every prime up to it.

a loop inside a function · the function called inside a loop

on the screen

Up to: 30

2 3 5 7 11 13 17 19 23 29

Up to: 10

2 3 5 7

the code

def is_prime(n):
    count = 0
    for d in range(1, n + 1):
        if n % d == 0:
            count += 1
    return count == 2

n = int(input("Up to: "))
for k in range(2, n + 1):
    if is_prime(k):
        print(k, end=" ")
print()
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

Exercise 5

How to submit

  1. 1 download week06_exercise.zip from e-Class · unzip it: three files, one per problem
  2. 2 put the three files in python_course/week06 · open them in VS Code
  3. 3 in each file: write the missing code · save · run it and try every example
  4. 4 zip the three files · upload the zip on e-Class · the deadline is in the post
10 points: 2 · 3 · 5attempted: full points, right or wronglate: half the pointsAI: allowed, but try alone first

Next steps

Now: exercise 5.

Before class. Everything you need is on e-Class.

See you in class.

← All weeks
01 / 00
Scroll · ↓ · Space