Python Part 4
Python Part 4
10 Python
Python Loops
• while loops
• for loops
1-While Loops
i = 1
while i < 6:
print(i)
i += 1 #i=i+1
We can run a series of statements while a condition is true by using the while loop.
With the else statement we can run a block of code once when the condition no longer is true:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
2- For Loops
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Page | 1
Done by Eng. Ahmad Al Matar
Computing Fundamentals Cs1150 Lab NO.10 Python
The range () function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range (5, 10), which means values from 5 to 10 (but not
including 10) and you can add a third parameter to specify the increment value:
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
for x in range(6):
print(x)
else:
print("Finally finished!")
Page | 2
Done by Eng. Ahmad Al Matar
Computing Fundamentals Cs1150 Lab NO.10 Python
1. Write a Python program to compute and print the sum of all integers between 5 and 20,
and then compute the average of these numbers.
3. Write a Python program to compute and print the sum and average of all even integers
between 0 and 100.
Page | 3
Done by Eng. Ahmad Al Matar