Form 4 - Computer

2024-2025

Floor 4 - Computer Room

Mr. Peter

While Loop & List

Santa Rosa de Lima English Secondary School

聖羅撒英文中學

Colégio de Santa Rosa de Lima - Secção Inglesa

Outline

List

1.

Explore the concept of List

How to process List in While Loop

2.

Focusing on the List processing in looping

Python List implementation

3.

Define while loop statement for List scanning

What is List?

What is List?

0

1

...

[

]

2

1

4

1

1

1

3

1

boxes = 

In Python:

boxes = [ 1, 1, 1, 1, 1 ]
print( boxes[ 0 ] )

Get variable from List

list[ position ]

Output: 1

What is List?

0

a

"

"

2

c

4

e

1

b

3

d

text = 

We can also get letter from text

text = "abcde"
print( text[ 0 ] )

Get letter from text

Output: a

text[ position ]

Python List Exercises

Python List - Ex01

Print All Odd Numbers in a List

1.

Use a while loop to iterate through the numbers.

1

Print the digit if digit is equal to Odd number

2

digits = [1, 2, 6, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4, 2, 6, 3, 4, 6, 4, 3, 5]

(  The variable "i" increases from 0 to len(digits) )

Save your file as "ClassNumber_YourName_Ex01.py"

Print the result

3

1
3
5
1
3
1
3
3
3
5

Expected output:

Python List - Ex02

Write a program to count how many times "2" element appears in a given list using a while loop.

1.

Use a while loop to iterate through the numbers.

1

Increase count variable if digit is equal to "2"

2

digits = "1263451234123426346435"

(  The variable "i" increases from 0 to len(digits) )

Save your file as "ClassNumber_YourName_Ex02.py"

Print the accumulated result

3

4

Expected output:

Python List - Ex03

Write a Python program to find the largest number in a list using a while loop.

2.

Use a while loop to iterate through the numbers.

1

Update the maximum number if the current number is greater than the stored value.

2

numbers = [3, 1, 4, 1, 5, 9, 1, 2, 7, 3, 10, 13, 4, 6, 7, 1, 2, 6, 9, 5, 3]

(  The variable "i" increases from 0 to len(numbers) )

Save your file as "ClassNumber_YourName_Ex03.py"

Print the accumulated result

3

13

Expected output: