Python Programming · Week 7
Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering
>>>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
>>>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'
to keep the new string: store it
a new string
>>>" hi ".strip()
'hi'
>>>"Hello".lower()
'hello'
>>>"hello".upper()
'HELLO'
>>>"010-1234-5678".replace("-", " ")
'010 1234 5678'
>>>", ".join(["Kim", "Lee", "Park"])
'Kim, Lee, Park'
a list
>>>"85 72 93".split()
['85', '72', '93']
>>>"Kim,Lee,Park".split(",")
['Kim', 'Lee', 'Park']
True or False
>>>"2026".isdigit()
True
>>>"20a6".isdigit()
False
>>>"Python".startswith("Py")
True
>>>"photo.png".endswith(".png")
True
immutable a string cannot change · string methods return a new value
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
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 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)
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
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
No computer. Say what comes out, then I run it.
>>>nums = [10, 20, 30, 40, 50]
>>>nums[1:-1]
>>>nums[::-2]
>>>"Le" in ["Kim", "Lee"]
>>>a = [1, 2]
>>>b = a
>>>c = a.copy()
>>>a.append(3)
>>>b
>>>c
quiz4.py
def reset(items):
items = []
data = [1, 2]
reset(data)
print(data)
quiz5.py
def swap(x, y):
x, y = y, x
p = 1
q = 2
swap(p, q)
print(p)
quiz6.py
for i, ch in enumerate("hi"):
print(f"{i}: {ch}")
A palindrome reads the same forwards and backwards, such as level. Ask for a word in lowercase letters. If it is a palindrome, print Palindrome. If not, print Not a palindrome.
on the screen · one run
Word: level
Palindrome.
the value after the prompt is typed · the prompt word is up to you
examples · typed values in order
typed
prints
level
Palindrome.
python
Not a palindrome.
racecar
Palindrome.
noun
Not a palindrome.
a
Palindrome.
Ask for a binary number (only 0s and 1s), and print its value as a decimal number. For example, 1011 is 8 + 0 + 2 + 1 = 11.
on the screen · one run
Binary: 1011
Decimal: 11
the value after the prompt is typed · the prompt word is up to you
Hint: go through the digits from the right (a slice can reverse a string); their place values are 1, 2, 4, 8, …
examples · typed values in order
typed
prints
1011
Decimal: 11
11111111
Decimal: 255
100000
Decimal: 32
0
Decimal: 0
1
Decimal: 1
A sensor is read several times. Ask how many readings there are, then each reading. Print the average, then each reading that is more than 10% off, with its position: more than 10% off means its difference from the average is more than 10% of the average.
on the screen · one run
How many readings? 4
Reading 1: 5.1
Reading 2: 6.0
Reading 3: 4.9
Reading 4: 4.0
Average: 5.0
Reading 2: 6.0 is more than 10% off.
Reading 4: 4.0 is more than 10% off.
the values after the prompts are typed · the prompt words are up to you
steps, in words
examples · typed values in order
typed
prints
4, 5.1, 6.0, 4.9, 4.0
Average: 5.0, then readings 2 and 4
3, 4.8, 5.0, 5.2
Average: 5.0 only
1, 7.5
Average: 7.5 only
5, 12.0, 9.8, 10.2, 10.1, 7.9
Average: 10.0, then readings 1 and 5
Next week
Midterm: Monday, October 26, 8:00–8:50 a.m., Changhak Hall 123.
Exercise 6: due tomorrow, Tuesday, October 20, 11:59 a.m.
Week 9 videos and exercise 7: up Tuesday–Wednesday, October 27–28.
Slides: hyeongminlee.github.io/slides/python-programming