Python Programming · Week 7
Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering
n = int(input("How many scores? "))
total = 0
for i in range(1, n + 1):
score = int(input(f"Score {i}: "))
total += score
print(f"Average: {total / n}")
How many scores? 4
Score 1: 85
Score 2: 72
Score 3: 93
Score 4: 60
Average: 77.5
How many scores are above the average?
after the loop
the loop adds each score, then forgets it · keep them all?
n = int(input("How many scores? "))
scores = []
for i in range(1, n + 1):
score = int(input(f"Score {i}: "))
scores.append(score)
average = sum(scores) / len(scores)
above = 0
for score in scores:
if score > average:
above += 1
print(f"Scores: {sorted(scores)}")
print(f"Average: {average}")
print(f"Highest: {max(scores)}, lowest: {min(scores)}")
print(f"Above the average: {above}")
←an empty list
←one more item each time
←every score again, after the loop
←built-in functions for lists
How many scores? 4
Score 1: 85
Score 2: 72
Score 3: 93
Score 4: 60
Scores: [60, 72, 85, 93]
Average: 77.5
Highest: 93, lowest: 60
Above the average: 2
a list: many values in one variable · use them again, any time
>>>scores = [85, 72, 93, 60]
>>>len(scores)
4
>>>names = ["Kim", "Lee"]
>>>len([])
0
items, in order →
strings, too
empty: 0 items
a list: values in order, in one variable · len counts them
>>>scores = [85, 72, 93, 60]
>>>scores[0]
85
>>>scores[3]
60
>>>scores[-1]
60
>>>scores[-2]
93
>>>scores[4]
IndexError: list index out of range
scores[start:stop]
[:2] is [0:2]: from the beginning
[2:]: from index 2 to the end
>>>scores = [85, 72, 93, 60]
>>>scores[1:3]
[72, 93]
>>>scores[:2]
[85, 72]
>>>scores[2:]
[93, 60]
like range(1, 3) → 1, 2
scores[start:stop:step]
like range(0, 3, 2) → 0, 2
[::2]: from the beginning to the end
>>>scores = [85, 72, 93, 60]
>>>scores[0:3:2]
[85, 93]
>>>scores[::2]
[85, 93]
>>>scores[::-1]
[60, 93, 72, 85]
the step: how far to move each time · [::-1]: reversed
>>>word = "Python"
>>>word[0]
'P'quotes: a string
>>>word[-1]
'n'
>>>word[0:3]
'Pyt'
>>>word[::-1]
'nohtyP'
>>>len(word)
6
a string: characters in order · the same indexes, the same slices
>>>scores = [85, 72, 93, 60]
>>>scores[1] = 75
change an item
>>>scores.append(88)
add at the endmethod
>>>scores.insert(0, 90)
add at a position
>>>scores.pop()
take out the last · returns 88
>>>scores.remove(93)
remove a value
a list can change · list methods change the list itself
>>>word = "Python"
>>>word[0] = "J"
TypeError: 'str' object does not support item assignment
>>>word.upper()
'PYTHON'
>>>word
'Python'unchanged
>>>word = word.upper()
>>>word
'PYTHON'
cannot be changed
to keep the new string: store it
a string is immutable · a string method returns a new string
>>>" hi ".strip()
'hi'
spaces off both ends
>>>"Hello".lower()
'hello'
lowercase
>>>"hello".upper()
'HELLO'
uppercase
>>>"2026".isdigit()
True
only digits?
>>>"20a6".isdigit()
False
>>>"Python".startswith("Py")
True
starts with ...?
>>>"photo.png".endswith(".png")
True
ends with ...?
scores = [85, 72, 93, 60]
for score in scores:score = 85score = 72score = 93score = 60
print(score)
85
72
93
60
no more items: the loop ends
the loop variable takes the items in turn · range gives numbers, a list gives its items
scores = [85, 72, 93, 60]
a string
for ch in "hi!":
print(ch)
h
i
!
positions
for i in range(len(scores)):
print(f"{i}: {scores[i]}")
0: 85
1: 72
2: 93
3: 60
a string: one character at a time · range(len(...)): when you need the positions
>>>scores = [85, 72, 93, 60]
>>>85 in scores
True
>>>70 in scores
False
>>>"@" in "kim@seoultech.ac.kr"
True
>>>"z" in "hello"
False
x in items: True or False · for a list, and for a string
>>>scores = [85, 72, 93, 60]
>>>len(scores)
4
how many
>>>sum(scores)
310
the total
>>>min(scores)
60
the smallest
>>>max(scores)
93
the largest
>>>sorted(scores)
[60, 72, 85, 93]
a new list, sorted
>>>scores
[85, 72, 93, 60]
unchanged
len, sum, min, max · sorted: a new list, the old one unchanged
scores = [85, 72, 93, 60]
new = sorted(scores)
print(new)
print(scores)
[60, 72, 85, 93]
[85, 72, 93, 60]
a new list · scores unchanged
scores = [85, 72, 93, 60]
scores.sort()
print(scores)
[60, 72, 85, 93]
scores itself is sorted
sorted(): a new list · .sort(): changes the list, returns None
>>>"85 72 93".split()
['85', '72', '93']
a string → a list
>>>"Kim,Lee,Park".split(",")
['Kim', 'Lee', 'Park']
>>>", ".join(["Kim", "Lee", "Park"])
'Kim, Lee, Park'
a list → a string
>>>"010-1234-5678".replace("-", " ")
'010 1234 5678'
the pieces are strings: '85', not 85
split: a string into a list · join: a list into a string
a number · as in week 3
a = 10
b = a
b = b + 1
print(b)
print(a)
11
10
a list
a = [10, 20, 30]
b = a
b[0] = b[0] + 1
print(b[0])
print(a[0])
11
?11
b = b + 1: a new value for the variable · b[0] = b[0] + 1: a change to the one list
a = [10, 20, 30]
c = a.copy()
c[0] = c[0] + 1
print(c[0])
print(a[0])
11
?10
.copy(): a new list · a change to one leaves the other as it is
a number · week 6
def add_bonus(score):
score = score + 5
score = 80
add_bonus(score)
print(score)
a list
def add_bonus(scores):
scores[0] = scores[0] + 5
scores = [80, 70]
add_bonus(scores)
print(scores[0])
?85
a new value for a parameter stays inside · a change to a list shows outside
>>>point = (3, 4)
>>>point[0]
3
>>>len(point)
2
>>>point[0] = 5
TypeError: 'tuple' object does not support item assignment
like a string
a tuple: values in parentheses · fixed, it cannot change
point = (3, 4)
x, y = point
print(x)
print(y)
3
4
unpacking one variable for each value · in order
a = 1
b = 2
a, b = b, a
print(a)
print(b)
2
1
↓
↓
↓
the right side first, as one tuple · then one value for each variable
week 5
a = 3
b = 5
c = a + b
a = b
b = c
unpacking
a = 3
b = 5
a, b = b, a + b
↓
↓
↓
the right side uses the old a and b · no c needed
def min_max(scores):
return min(scores), max(scores)
print(min_max([85, 72, 93, 60]))
low, high = min_max([85, 72, 93, 60])
print(f"{low} {high}")
(60, 93)
60 93
↓
↓
return a, b: one tuple · unpack it at the call
scores = [85, 72, 93, 60]
for i, score in enumerate(scores, start=1):i, score = (1, 85)i, score = (2, 72)i, score = (3, 93)i, score = (4, 60)
print(f"{i}: {score}")
1: 85
2: 72
3: 93
4: 60
enumerate: (position, item) tuples · unpacked in the for line
n = int(input("How many scores? "))
scores = []
for i in range(1, n + 1):
score = int(input(f"Score {i}: "))
scores.append(score)
average = sum(scores) / len(scores)
above = 0
for score in scores:
if score > average:
above += 1
print(f"Scores: {sorted(scores)}")
print(f"Average: {average}")
print(f"Highest: {max(scores)}, lowest: {min(scores)}")
print(f"Above the average: {above}")
←[]: an empty list
←append: one more item
←sum, len
←for over the list: the scores again
←sorted, max, min
a list keeps the values · use them again, as often as you need
Next steps
Have Python open. Type everything with me.
See you in class.