Complete Guide to Python Loops
There are two loop statments in python.
- while
- for-in
while
- Print the sequence 1, 5, 13, 29, … 8189.
num = 1
while num <= 8189:
print(num)
num = 2*num + 3
for-in
- Print the sequence 3, 7, 11, 15, … 99.
for i in range(3, 100, 4):
print(i)
Interview Questions
1. What are the three python keywords related to python loops?
- break
- continue
- else
2. When will else-block be excuted in a loop?
when no break occurs.
import random
for i in range(1, random.randint(5, 15)):
if i > 10:
break
print(i)
else:
print("Printed all the numbers!")