Grade 09 - Topic 02 – Programming and Development
NOTE - PART II
How to implement Repetition Control Structure in Python
❖ In Python, we can use following code blocks to implement Repetition Control Structure:
➢ WHILE Loop.
➢ FOR Loop.
While Loop in Python
❖ Example 01: Write a complete program in Python using while loop to display 5 stars, one at each line.
Code Output
counter = 1 Loop starts now!
print("Loop starts now!") *
#Starting the Loop *
while(counter<=5): *
print("*") *
counter+=1 *
#Loop is closed Loop is finished!
print("Loop is finished!")
❖ Example 02: Write a complete program in Python using while loop to display numbers from 1 to 5
(including both 1 and 5) according to the ascending order, one number at each line.
Code Output
counter = 1 1
2
while(counter<=5): 3
print(counter) 4
counter+=1 5
Tuesday, October 18, 2022 Page 1 of 3
Grade 09 - Topic 02 – Programming and Development
NOTE - PART II
❖ Example 03: Write a complete program in Python using while loop to display numbers from 10 to 6
(including both 10 and 6) according to the descending order, one number at each line.
Code Output
counter = 10 10
9
while(counter>5): 8
print(counter) 7
counter-=1 6
For Loop in Python
❖ Example 01: Write a complete program in Python using for loops to display 5 stars, one at each line.
Code Output
print("Loop starts now!") Loop starts now!
#Starting the Loop *
for counter in range(5): *
print("*") *
#Loop is closed *
print("Loop is finished!") *
Loop is finished!
➢ range( ) function takes a number as the input gives you a sequence of numbers starting from 0
and increments by 1 by default.
➢ Example:
▪ range(2) → 0,1 (2 numbers)
▪ range(5) → 0,1,2,3,4 (5 numbers)
➢ Read more: Click here.
Tuesday, October 18, 2022 Page 2 of 3
Grade 09 - Topic 02 – Programming and Development
NOTE - PART II
❖ Example 02: Write a complete program in Python using for loop to display numbers from 0 to 4
(including both 0 and 4) according to the ascending order, one number at each line.
Code Output
for counter in range(5): 0
print(counter) 1
2
3
4
❖ Example 03: Write a complete program in Python using for loop to take marks of 5 subjects and save
them in a list. Once complete storing user input, program must display all the values currently stored
in the list.
Code
#Creating the list with initial values to store marks
studentMarks = [0,0,0,0,0]
for indexNumber in range(5):
studentMarks[indexNumber] = int(input("Enter Marks: "))
print("Inserted marks are:",studentMarks)
Sample Output
Enter Marks: 75
Enter Marks: 80
Enter Marks: 88
Enter Marks: 79
Enter Marks: 80
Inserted marks are: [75, 80, 88, 79, 80]
Tuesday, October 18, 2022 Page 3 of 3