For and While Loops in Python
Loops repeat a block of code. Python has two loops: for goes through every item of a sequence (string, list, dictionary, range), and while repeats as long as a condition is True.
for Loop over a String and a List
x = "Sudheer"
for letter in x:
print(letter)
numbers = [10, 20, 62, 45]
for item in numbers:
print(item)
Nested loop over a list of strings
fruits = ["Banana", "Orange", "Apple", "Mango", "Papaya"]
for fruit in fruits:
print(fruit)
for letter in fruit: # inner loop goes through each letter
print(letter)
break: Stop the Loop
break exits the loop as soon as a condition is met. Where you put print decides whether the matching item is printed.
fruits = ["Banana", "Orange", "Apple", "Mango", "Papaya"]
# print first, then check -> Apple IS printed
for fruit in fruits:
print(fruit)
if fruit == "Apple":
break
# check first, then print -> Apple is NOT printed
for fruit in fruits:
if fruit == "Apple":
break
print(fruit)
continue: Skip One Item
continue skips the rest of the current iteration and moves to the next item.
for fruit in fruits:
if fruit == "Orange":
continue # Orange is skipped
print(fruit)
Looping with range()
for x in range(6): # 0 to 5 (6 is not included)
print(x)
for x in range(2, 18): # 2 to 17
print(x)
for x in range(2, 20, 2): # 2, 4, 6 ... 18 (step of 2)
print(x)
for x in range(10, 0, -1): # reverse: 10 down to 1
print(x)
for Loop with else
The else block runs only when the loop finishes normally, that is, without break.
for x in range(50):
if x == 32:
break
print(x)
else:
print("Loop finished") # not printed, because the loop was broken at 32
Looping Through a Dictionary
employee = {"name": "Rahul", "age": 30, "salary": 75000}
for key in employee: # keys
print(key)
for value in employee.values(): # values
print(value)
for key, value in employee.items(): # keys and values
print(key, ":", value)
Nested Loops
for i in range(1, 4):
for j in range(1, 4):
print(i, j) # 9 combinations
# multiplication tables of 1, 2 and 3
for i in range(1, 4):
for j in range(1, 11):
print(i, "x", j, "=", i * j)
print()
break and continue in nested loops
break and continue affect only the loop they are written in (the inner loop here).
for i in range(1, 4):
for j in range(1, 4):
if j == 2:
break # leaves the inner loop only
print(i, j)
for i in range(1, 4):
for j in range(1, 4):
if j == 2:
continue # skips j == 2 only
print(i, j)
while Loop
A while loop runs as long as its condition is True. Always change the variable inside the loop, or it never ends.
i = 1
while i <= 5:
print(i)
i += 1
while with break
i = 1
while i <= 5:
print(i)
if i == 3:
break
i += 1
Nested while loop
i = 1
while i <= 3:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 1
while with continue: reading user input
user_input = input("Enter a number: ")
while user_input != "exit":
if user_input == "skip":
print("Skipping this iteration")
user_input = input("Enter a number: ")
continue
print("You entered:", user_input)
user_input = input("Enter a number: ")
Real Example: Login Attempts with while-else
The user gets 3 attempts. The else block runs only if the loop ends without a successful login (no break).
correct_password = "admin123"
attempts = 3
while attempts > 0:
password = input("Enter password: ")
if password == correct_password:
print("Login successful")
break
attempts -= 1
print("Invalid password")
else:
print("Account locked")