Lecture Module 4 - Repeating Parts
Lecture Module 4 - Repeating Parts
➢ Repeating structure
➢ While Loop
➢ For Loop
➢ Exit condition within loops (pass, break,
continue)
➢ Nested loop
For example:
You need to convert 50 students’ results data to
grade. The calculation method for each student is the
same.
process process
true
Condition process
false
process
while condition:
# Code to be repeated as long as the condition is true
The process looping Try this simple program and learn from the result
continues until
certain condition for i in range(1, 6):
then it will stop. print(i)
print('end program')
Predefined items/counts
false
Last item/count reached process
true
process
The process looping Try this simple program and learn from the result
continues according
to the predefined for i in range(1, 6):
counts then it will print(i)
stop. print('end program')
count = 0
while (count < 9): i=1
print ("The count is: ", count) while i <= 5:
count = count + 1 print(i)
I += 1 # this is identical with i = i +1
print ("Good bye!")
print ("Good bye!")
total = 0
print('end program')
print('end program')
print('end program')
for i in range(5):
if i == 2:
pass # Placeholder, does nothing
else:
print(i)
print('outside loop')
You have a program to classify a triangle and to calculate the area of the triangle
based on Heron’s formula in Example 3-7.
Now you want to improve the program so you can repeat for different data, until
you want to stop (no more data), by using While structure.
If you enter
number_control = 0
then the program will
not request another
data
What is the
difference with the
previous one?
Now add the feature in example 4-4 to classify the triangle by the angle.
The calculation of the angle by using cosine rules
Python programming language allows the use of one loop inside another loop. The
following sections show some examples to illustrate the concept.
Write a code to help a teacher to calculate the average of each student tests in the
class.
●
The number of the students and the number of the test should be defined in the
program by entering the number than used in program as range of for nested loop.
●
The average score for each student should be calculated
●
The overall average should be calculated