Introduction to Python

Form 3 - Computer

2023-2024

Floor 4 - Computer Room

Mr. Peter

Outline

Outline

While Loop

1

Number Sequences

2

Exercises

3

While Loop Statement

1.

2.

Tab

while Condition :

Command1

While Loop Statement

1.

2.

while i < 5 :

3.

Tab

4.

Tab

i = 0

print(i)

i = i + 1

Write a Python code to create a loop printing number from 30 to 0, each loop decreases 5.

Question

While loop statement - Ex01

30

25

20

......

10

5

0

Example

Save the file as "XX_YYYY_Ex01.py"

Write a Python code to create a loop printing number from 100 to 0, then 0 to 100, each loop increase or decrease 1.

Question

While loop statement - Ex02

100

99

98

...

3

2

1

0

1

2

3

...

98

99

100

Example

Save the file as "XX_YYYY_Ex02.py"

Write a Python code to create a loop printing number from 100 to 0, then 0 to 100, each loop increase or decrease 1.

Question

While loop statement - Ex02

100

99

98

...

3

2

1

0

1

2

3

...

98

99

100

Example

Save the file as "XX_YYYY_Ex02.py"

Write a Python program that calculates and prints the values of 𝑦 for 𝑥 ranging from 1 to 20, where 𝑦 is defined by the equation              . Your program should use a for loop to iterate through the values of 𝑥 and print the corresponding 𝑦 values.

Question

While loop statement - Ex03

x = 1, y = 2
x = 2, y = 4
x = 3, y = 8

x = 4, y = 16
...

x = 19, y = 524288
x = 20, y = 1048576

Example

Save the file as "XX_YYYY_Ex03.py"

y = 2^x
y = 2^x
print( 'x = ', x, ', y = ', y )

String concatenation for printing

* Consider looping x from 1 to 20, then loop y from 1 to 1048576 within the same while loop.

Python - While Loop 03

By Mr Peter

Python - While Loop 03

  • 152