Control Flow
Loops: for, while & range
Iterate with for over any sequence, count with range(), repeat with while, control loops with break, continue and the loop else clause, and write the classic loop programs.
for loops
Python's for loops over the items of any iterable — a list, string, range, dictionary, file …
Python
for subject in ["C", "DSA", "Python"]:
print("Studying", subject)
for ch in "abc":
print(ch.upper(), end=" ")
print()Output
Studying C Studying DSA Studying Python A B C
range()
range(start, stop, step) produces numbers from start up to but not including stop:
Python
print(list(range(5))) # 0..4
print(list(range(2, 10, 3))) # 2, 5, 8
print(list(range(10, 0, -2))) # counting down
for i in range(1, 6):
print(f"7 x {i} = {7 * i}")Output
[0, 1, 2, 3, 4] [2, 5, 8] [10, 8, 6, 4, 2] 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
enumerate and zip
Python
names = ["Asha", "Ravi", "Meera"]
marks = [91, 78, 85]
for i, name in enumerate(names, start=1):
print(i, name)
for name, m in zip(names, marks):
print(f"{name:6} {m}")Output
1 Asha 2 Ravi 3 Meera Asha 91 Ravi 78 Meera 85
while loops
Use while when you do not know in advance how many times to repeat:
Python
total = 0
count = 0
n = int(input("Number (0 to stop): "))
while n != 0:
total += n
count += 1
n = int(input("Number (0 to stop): "))
print(f"{count} numbers, sum {total}")Output
Number (0 to stop): 5 Number (0 to stop): 12 Number (0 to stop): -3 Number (0 to stop): 0 3 numbers, sum 14
Sample input is includedTry it Yourself
break, continue and loop-else
breakleaves the loop immediately.continueskips to the next iteration.- A loop's
elseblock runs only if the loop finished withoutbreak— perfect for searches.
Python
def is_prime(n):
if n < 2:
return False
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break # found a divisor
else:
return True # no break: no divisor found
return False
print([n for n in range(1, 40) if is_prime(n)])
for n in range(1, 11):
if n % 3 == 0:
continue
print(n, end=" ")
print()Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] 1 2 4 5 7 8 10
Classic loop programs
Python
# Fibonacci
a, b = 0, 1
fib = []
for _ in range(12):
fib.append(a)
a, b = b, a + b
print("Fibonacci:", fib)
# Sum of digits and reverse
n = 40213
digits = 0
rev = 0
while n > 0:
digits += n % 10
rev = rev * 10 + n % 10
n //= 10
print("digit sum:", digits, "reversed:", rev)
# Armstrong numbers
arm = [n for n in range(1, 1000) if n == sum(int(d) ** len(str(n)) for d in str(n))]
print("Armstrong:", arm)
# GCD with Euclid's algorithm
x, y = 84, 36
while y:
x, y = y, x % y
print("gcd(84, 36) =", x)Output
Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] digit sum: 10 reversed: 31204 Armstrong: [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407] gcd(84, 36) = 12
Pattern printing
String multiplication makes patterns much shorter than in C:
Python
n = 5
for i in range(1, n + 1):
print("* " * i)
print()
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
print()
for i in range(1, n + 1):
print(" ".join(str(j) for j in range(1, i + 1)))Output
*
* *
* * *
* * * *
* * * * *
*
***
*****
*******
*********
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5Test yourself
4 questions · pick an answer to check it instantly
- 1
What does
list(range(3, 12, 4))produce?Start at 3, step 4, stop before 12. - 2
When does a
forloop'selseblock run?elseon a loop means "completed normally". - 3
How many times does this print?
Pythoni = 10 while i > 0: print(i) i -= 3itakes the values 10, 7, 4 and 1. - 4
What does
print("ab" * 3)output?Multiplying a string repeats it.