Python Programming · Week 6
Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering
A new folder for this week.
This video is all typing. Pause whenever you need to catch up.
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
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>
report waits while grade runs · the call stack: the calls still waiting
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
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
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() 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
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
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() 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.
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.
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)}")
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 steps
Before class. Everything you need is on e-Class.
See you in class.