Loop Note
Loop Note
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
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
import random
n = 20
to_be_guessed = int(n * random.random()) + 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
Execute Statement(s)
End
EXAMPLES OF FOR LOOP
1 for i in range(7):
print(i)
print(“Good bye”)
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