LOOPS
Loops are used to create repetition.
Programs that contain repeating lines of code can be time-consuming
to type in and difficult to understand. A clearer way of writing them is
by using a loop command.
TYPES OF LOOPS
WHILE LOOP: They are known as indefinite or conditional loops. They
will keep iterating until certain conditions are met. There is no
guarantee that ahead of time regarding how many times the loop will
iterate.
Start
False
While
Condition?
True
Body of the loop
Exit
A SIMPLE EXAMPLE OF WHILE LOOP
Count = 0
while count<9
print(“Number:”, count)
count = count +1
print(“Good bye”)
Let’s Do A little guessing game
Let the correct answer be 13
Input Number: 10 Number is too small
Input Number: 15 Number is too large
Input Number: 13 Exit: Congratulations. You made it!
import random
n = 20
to_be_guessed = int(n * [Link]()) + 1
guess = 0
while guess != to_be_guessed:
guess = int(input(“New Number: ))
if guess > 0:
if guess > to_be_guessed:
print(“Number too large”)
elif guess < to_be_guessed:
print(“Number too small”)
else:
print(“Sorry that you’re giving up!”)
break
else:
print(“Congratulations. You made it!”)
FOR LOOP: This is a Python loop which repeats a group of
statements a specified number of times. The for loop
provides a syntax where the following information is
provided:
• Boolean condition
• The initial value of the counting variable
• Increment of counting variable
Start
If no more items
in the sequence
Item from
sequence
Next item from
sequence
Execute Statement(s)
End
EXAMPLES OF FOR LOOP
1 for i in range(7):
print(i)
This example will print out numbers: 0 1 2 3 4 5 6
2 for i in range(3, 9):
print(i)
This example will print out numbers: 3 4 5 6 7 8
3 for i in range(3, 9, 2):
print(i)
This example will print out numbers: 3 5 7
4 for i in range(9, 3, -1):
print(i)
This example will print out numbers: 9 8 7 6 5 4
fruits = [‘Mango’, ‘Grapes’, ‘Apple’]
for fruit in fruits:
print(“current fruit: “, fruit)
print(“Good bye”)
PROGRAM TO FIND THE FACTORIAL OF A
NUMBER
Factorial of a positive integer (number) is the sum of
multiplication of all the integers smaller than that positive
integer. For example, factorial of 5 is 5*4*3*2*1 which equals
to 120.
num = int(input(“Number: “))
factorial = 1
if num < 0:
print(“must be positive”)
elif num == 0:
print(“factorial = 1”)
else:
For i in range(1, num + 1):
factorial = factorial * i
print(factorial)
NESTED LOOP: This type of loop allows use of loop inside another
loop. In nested loops, the outer loop only repeats after the inner loop
has gone round its required number of times
n = 3
for a in range(1, n + 1):
for b in range(1, n + 1):
print(b, “X”, a, “=“ , b * a)
CLASSWORK
Write a nested loop that will
calculate 1 to 12 Times-table and
display it in a proper
arrangement.
PROJECT