Python Programming · Week 7

Lists and Tuples
Practice

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

Setup

Before we start

A new folder, and the prompt for a drill.

  1. 1 VS Code → open your python_course folder
  2. 2 New Folder → week07
  3. 3 Terminal → python3 → the >>> prompt
Drill

Predict, then type

On paper: what comes out? Then type each line at the prompt.

a string

>>>word = "voltage"

>>>word[1]

>>>word[-1]

>>>word[:4]

>>>word[4:]

>>>word[::-1]

a list

>>>nums = [3, 1, 4, 1, 5, 9]

>>>nums[2] + nums[-2]

>>>nums[1:4]

>>>nums[::2]

>>>nums[len(nums)]

digits in a string

>>>year = "2026"

>>>year[0] + year[-1]

>>>int(year[0]) + int(year[-1])

>>>"0" in year

Files

stats.py

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

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}")

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

Debugger

Watch the list grow

1n = int(input("How many scores? "))

2scores = []

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

4 score = int(input(f"Score {i}: "))

5 scores.append(score)

6

7average = sum(scores) / len(scores)

⋮

scores in VARIABLES

one append at a time

[]

[85]

[85, 72]

[85, 72, 93]

[85, 72, 93, 60]

opened with ▸

085172293360len()4
  1. 1 click just left of line 2's number: a breakpoint
  2. 2 the small arrow next to ▷ → Python Debugger: Debug Python File · type 4 in the terminal
  3. 3 Step Over (F10): scores appears in VARIABLES, empty
  4. 4 Step Over again and again · type each score in the terminal
  5. 5 after the loop: click ▸ next to scores
  6. 6 ▷ Continue: to the end
  7. Mac: F10 may need fn · or click the Step Over icon
Drill

Break three things

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

the append line

delete it

ZeroDivisionError: division by zero

the list stays empty: len(scores) is 0

the append line

store what it returns: scores = scores.append(score)

AttributeError: 'NoneType' object has no attribute 'append'

append returns None, so now scores is None

the Scores line

change sorted(scores) to scores.sort()

Scores: None

Average: 77.5

Highest: 93, lowest: 60

Above the average: 2

.sort() sorts the list and returns None

append, .sort(): they change the list · and return None

Example · 1

Count the vowels

vowels.py

Ask for a word. Print how many vowels it has: a, e, i, o, u.

for ch in word: one character per iteration · ch in "aeiou": True or False

on the screen

Word: banana

Vowels: 3

Word: Education

Vowels: 5

the code

word = input("Word: ").lower()
count = 0
for ch in word:
    if ch in "aeiou":
        count += 1
print(f"Vowels: {count}")
Example · 2

Digit sum, again

digits.py

Ask for an integer, 0 or more. Print the sum of its digits.

week 5 used % 10 and // 10 · now: the typed string, one character at a time

on the screen

Number: 2026

Digit sum: 10

Number: 99999

Digit sum: 45

the code

number = input("Number: ")
total = 0
for digit in number:
    total += int(digit)
print(f"Digit sum: {total}")

week 5

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

total = 0

while n > 0:

total += n % 10

n = n // 10

print(f"Digit sum: {total}")

Example · 3

Long words

words.py

Ask for a sentence. Print the average length of its words, then each word longer than the average, with its position.

on the screen · one run

Sentence: Python is easy to learn

Average length: 3.8

Word 1: Python

Word 3: easy

Word 5: learn

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

steps, in words

  1. 1 Split the sentence into a list of words.
  2. 2 Work out the average length of the words.
  3. 3 Go through the list again, and print each word longer than the average, with its position.

examples · typed values in order

typed

prints

Python is easy to learn

Average length: 3.8, then words 1, 3, 5

Ohm's law is simple

Average length: 4.0, then words 1, 4

Hello world

Average length: 5.0 only

Example · 3

Long words: the program

words.py

under the comments: one block per step

# Write your program here.

sentence = input("Sentence: ")

words = sentence.split()

1

total = 0

for word in words:

total += len(word)

average = total / len(words)

print(f"Average length: {average}")

2

for i, word in enumerate(words, start=1):

if len(word) > average:

print(f"Word {i}: {word}")

3

on the screen · one run

Sentence: Python is easy to learn

Average length: 3.8

Word 1: Python

Word 3: easy

Word 5: learn

  1. 1 Split the sentence into a list of words.
  2. 2 Work out the average length of the words.
  3. 3 Go through the list again, and print each word longer than the average, with its position.
Exercise 6 · Problem 1

Palindrome

week07_problem1.py 2 points

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.

Exercise 6 · Problem 2

Binary to decimal

week07_problem2.py 3 points

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

Exercise 6 · Problem 3

Readings off the average

week07_problem3.py 5 points

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

  1. 1 Read the readings into a list.
  2. 2 Work out the average.
  3. 3 Go through the list again, and print each reading that is more than 10% off, with its position.

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

Exercise 6

How to submit

  1. 1 download week07_exercise.zip from e-Class · unzip it: three files, one per problem
  2. 2 put the three files in python_course/week07 · open them in VS Code
  3. 3 in each file: write your program at the bottom · 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 6.

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

See you in class.

← All weeks
01 / 00
Scroll · ↓ · Space