Python loop
2 min readAug 16, 2025
🔹 While Loop
- A
whileloop runs as long as a condition is true. - Useful when we don’t know how many times to iterate beforehand.
Syntax:
while condition:
# code block✅ Examples:
- Basic while loop
i = 5
while i < 10:
print(i)
i += 1- Break Statement
i = 1
while i < 10:
print(i)
if i == 5:
break # exits loop immediately
i += 1- Continue Statement
i = 0
while i < 10:
i += 1
if i == 5:
continue # skips printing when i==5
print(i)- Nested while
counter = 1
while counter <= 3:
newcounter = 1
while newcounter <= 2:
print(counter, newcounter)
newcounter += 1
counter += 1🔹 For Loop
- A
forloop is used to iterate over a sequence (list,string,range, etc.).
Syntax:
for variable in sequence:
# code block✅ Examples:
- Iterating a list
list1 = ["1", "2", "3"]
for i in list1:
print(i)- Break Statement
names = ["kumar", "raja", "sam", "ram"]
for i in names:
if i == "sam":
break
print(i)- Continue Statement
Get Sowmithra’s stories in your inbox
Join Medium for free to get updates from this writer.
names = ["kumar", "raja", "sam", "ram"]
for i in names:
if i == "sam":
continue
print(i)- Pass Statement
for i in range(5):
if i == 3:
pass # does nothing, placeholder
print("i =", i)- Nested for loop
list1 = ["a", "b"]
list2 = [1, 2]
for i in list1:
for j in list2:
print(i, j)- Range function
for i in range(1, 11, 2): # start=1, stop=10, step=2
print(i)🔹 Pattern Programs
⭐ Square Pattern
n = 3
i = 1
while i <= n:
j = 1
while j <= n:
print("*", end=" ")
j += 1
print()
i += 1⭐ Right-angled Triangle
for i in range(1, 6):
for j in range(i):
print("*", end="")
print()⭐ Pyramid
n = 5
for i in range(1, n + 1):
print(" " * (n - i) + "* " * i)⭐ Diamond
n = 5
for i in range(1, n + 1):
print(" " * (n - i) + "* " * i)
for i in range(n - 1, 0, -1):
print(" " * (n - i) + "* " * i)🔹 Useful Programs
- Reverse a String
a = "sakthi"
b = ""
for i in a:
b = i + b
print(b) # 'ihtkas'- Remove Duplicates
lst = ['l', 'k', 's', 'l', 'm', 'k', 'm']
unique = []
for i in lst:
if i not in unique:
unique.append(i)
print(unique) # ['l','k','s','m']- Find Minimum
numbers = [5, 2, 8, 1, 6]
minimum = numbers[0]
for n in numbers:
if n < minimum:
minimum = n
print("Min:", minimum)



