Python Loops Made Easy: A Practical Guide to For and While Loops

What are Loops?
Loops are one of the most important concepts in python. Loops allows us to write the same block of code multiple times without rewriting it again and again. There are 2 types of loops in python for loop and While loop. Mastering loops will make your code efficient, readable and powerful.
Why we need Loops?
Take an example you want to print numbers from 1 to 100. Writing print() command for 100 times is impractical and time consuming. Here loops allows us to do the same task in few lines of code.
The for loop:
for loop in python is use to iterate over a sequence (list, tuple, string, range).
Example 1:
for i in range(1, 6):
print(i)
output: 1 2 3 4 5
Example 2:
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print("I like", fruit, sep=",")
output: I like apple, I like banana, I like mango
When to use for loop: When you know the number of iterations means you already know how many times you need to run the program or you want to go through the elements of collections.
The While loop:
The while loop will be in action until the condition is true.
Example 1: Counting till 5
count = 1 # initialized count as 1
while count <= 5: # set the condition while count is less than or equal to 5
print(count) # Print the values of count
count += 1 # Count will increment until it is equal to 5
Output: 1 2 3 4 5
Example 2: User controlled Loop
password = "" # Initialized password as an empty string
while password != "python123": # Set the condition that the value of password should be "python123"
password = input("Enter password: ") # while the above password is entered system keeps asking for the password
print("Access granted!") # Once the correct password is entered this message will appear.
When to use While Loop: When you don’t know the number of iterations means you don’t know how many times the loop should run and the stopping point depends on the condition given to while loop.\
Loop control statement
Sometimes you need extra control inside loops. Python provides special keywords for this:
break
→ exit the loop completelycontinue
→ skip the current iteration and move to the nextelse
with loops → runs only if the loop ends normally (not bybreak
)
Example: Using break
and continue
pythonfor num in range(1, 10):
if num == 5:
break # stop the loop when num is 5
if num % 2 == 0:
continue # skip even numbers
print(num)
Practical use case of loops
Data processing: Iterating through a dataset row by row
User input validation: Keep asking until correct input is given
Automation: Sending bulk emails or messages
Algorithm implementation: Searching, sorting, and traversing data structures
Subscribe to my newsletter
Read articles from Aditya Jaiswal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
