Contents:
- Introduction to Loops in Python
- for Loop in Python
- While Loop in Python
- Loop Control Statements in Python
- break Statement in Python
- continue Statement in Python
- pass Statement in Python
- Nested Loops in Python
- Looping Through Different Data Structures in Python
- Difference between for loop and while loop in Python
- Best Practices for Using Loops in Python
- FAQs on Loops in Python
Introduction to Loops in Python
Loops in Python are used to repeatedly execute a block of code until a condition is met. They reduce the need for manual repetition and make code more efficient. In Python, we primarily use for and while loops.
Types of Loops in Python
- for Loop: Iterates over a sequence (like lists, tuples, or strings).
- while Loop: Repeats as long as a condition is True.
for Loop in Python
The for loop iterates over a sequence (like a list, tuple, string, or range) and executes a block of code for each element.
Syntax of for Loop
for variable in sequence: # Code to execute in each iteration
Example:
subjects = ["Python", "Java", "C++"] # Loop through subjects for subject in subjects: print(f"Learning {subject}")
Output:
Learning Python Learning Java Learning C++
Using range() with for Loop:
The range() function generates a sequence of numbers, commonly used for looping a specific number of times.
Example:
for attempt in range(1, 4): print(f"Attempt {attempt}")
Output:
Attempt 1 Attempt 2 Attempt 3
Looping Through a String:
A for loop can be used to iterate through each character in a string. This is useful for performing operations on individual characters.
course = "Sanfoundry" # Loop through each character for char in course: print(char)
Output:
S a n f o u n d r y
While Loop in Python
The while loop in Python is used to repeatedly execute a block of code as long as a given condition is True.
Syntax of while Loop
while condition: # Code to execute
Example:
# Sanfoundry Quiz Attempts attempts = 1 # Loop until 3 attempts while attempts <= 3: print(f"Attempt {attempts}: Retake Quiz") attempts += 1
Output:
Attempt 1: Retake Quiz Attempt 2: Retake Quiz Attempt 3: Retake Quiz
Loop Control Statements in Python
Loop control statements modify the normal execution flow of loops (for and while), allowing better control over iteration.
Types of Loop Control Statements
- break Statement: Terminates the loop immediately.
- continue Statement: Skips the current iteration and moves to the next one.
- pass Statement: Does nothing and acts as a placeholder.
break Statement in Python
The break statement in Python is used to exit a loop prematurely when a certain condition is met. It works with both for and while loops, stopping execution immediately and moving to the next line of code outside the loop.
Syntax of break Statement
for/while loop: if condition: break
Example:
# Sanfoundry Quiz Attempts for attempt in range(1, 6): if attempt == 3: print("Quiz passed on attempt", attempt) break print(f"Attempt {attempt}: Retake required")
Output:
Attempt 1: Retake required Attempt 2: Retake required Quiz passed on attempt 3
Example: Using break in a while Loop
score = 40 # Increase score until passing while score < 50: print("Score too low. Retake required.") score += 5 if score >= 50: print("Passed!") break
Output:
Score too low. Retake required. Score too low. Retake required. Passed!
continue Statement in Python
The continue statement is used to skip the current iteration of a loop and move to the next iteration. It does not terminate the loop but skips any remaining code for that iteration.
Syntax of continue Statement
for/while loop: if condition: continue # Code to execute if condition is False
Example
# Sanfoundry Quiz Results subjects = {"Python": 85, "Java": 40, "C++": 90, "DBMS": 45} # Skip failed subjects for subject, score in subjects.items(): if score < 50: continue print(f"{subject}: Passed with score {score}")
Output:
Python: Passed with score 85 C++: Passed with score 90
Example: Using continue in a while Loop
# List of Course Progress progress = [100, 50, 75, 30, 90] i = 0 # Skip incomplete courses while i < len(progress): if progress[i] < 60: i += 1 continue print(f"Course {i + 1}: Completed with {progress[i]}% progress") i += 1
Output:
Course 1: Completed with 100% progress Course 3: Completed with 75% progress Course 5: Completed with 90% progress
pass Statement in Python
The pass statement is a placeholder that does nothing when executed. It is used when a block of code is syntactically required but not implemented yet.
Syntax of pass Statement
if condition: pass # Placeholder for future code
Example:
# Course List courses = ["Python", "Java", "C++"] for course in courses: if course == "Java": pass # Code for Java will be added later else: print(f"Learning {course}")
Output:
Learning Python Learning C++
Example with Function
# Placeholder function for future logic def check_score(score): if score < 50: pass # Logic to handle low scores will be added later else: print("Score is acceptable!")
Output:
(No output if score < 50, otherwise prints message)
Pass in a Class Example
# Placeholder class for future features class Quiz: pass # Create object q = Quiz() print("Quiz object created!")
Output:
Quiz object created!
Nested Loops in Python
Nested loops are loops inside another loop. The inner loop is executed completely for each iteration of the outer loop.
Syntax of Nested Loops
for outer_variable in outer_sequence: for inner_variable in inner_sequence: # Code to execute
Example 1:
# Sanfoundry Quiz Attempts for Subjects subjects = ["Python", "DBMS"] attempts = [1, 2, 3] for subject in subjects: for attempt in attempts: print(f"{subject} Quiz - Attempt {attempt}")
Output:
Python Quiz - Attempt 1 Python Quiz - Attempt 2 Python Quiz - Attempt 3 DBMS Quiz - Attempt 1 DBMS Quiz - Attempt 2 DBMS Quiz - Attempt 3
Example 2:
# Sanfoundry Retake Attempts subject_count = 2 attempt_count = 3 i = 1 while i <= subject_count: j = 1 while j <= attempt_count: print(f"Subject {i} - Retake {j}") j += 1 i += 1
Output:
Subject 1 - Retake 1 Subject 1 - Retake 2 Subject 1 - Retake 3 Subject 2 - Retake 1 Subject 2 - Retake 2 Subject 2 - Retake 3
Example 3: Multiplication Table
# Multiplication Table for 2 and 3 for num in [2, 3]: for i in range(1, 4): print(f"{num} x {i} = {num * i}") print("----")
Output:
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 ---- 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 ----
Looping Through Different Data Structures in Python
Python provides various ways to iterate through different data structures like lists, tuples, dictionaries, and sets.
1. Looping Through a List
# List of Sanfoundry Subjects subjects = ["Python", "Java", "DBMS"] for subject in subjects: print(f"Learning {subject}")
Output:
Learning Python Learning Java Learning DBMS
2. Looping Through a Tuple
topics = ("OS", "DSA", "Networks") for topic in topics: print(f"Studying {topic}")
Output:
Studying OS Studying DSA Studying Networks
3. Looping Through a Dictionary
scores = {"Python": 85, "Java": 90, "DBMS": 78} for subject, score in scores.items(): print(f"{subject} Score: {score}")
Output:
Python Score: 85 Java Score: 90 DBMS Score: 78
4. Looping Through a Set
# Set of Sanfoundry Certifications certs = {"AI", "ML", "Cloud"} for cert in certs: print(f"Certified in {cert}")
Output:
Certified in AI Certified in ML Certified in Cloud
Difference between for loop and while loop in Python
Here is the comparison between for loop and while loop in Python:
| Feature | for Loop | while Loop |
|---|---|---|
| Usage | Used when the number of iterations is known in advance (iterates over a sequence). | It is used when the number of iterations is unknown and depends on a condition. |
| Syntax | for variable in sequence: | while condition: |
| Condition Checking | No condition, uses sequence | Based on condition check |
| Best Used For | Iterating over lists, tuples, dictionaries, or a range of values. | Running loops until a condition is false (e.g., waiting for user input). |
| Example | for i in range(5): print(i) |
x = 0 |
| Loop Control | Works with iterables like lists, strings, and ranges. | Requires manual updates to the loop variable. |
Best Practices for Using Loops in Python
- Use for loops when looping through a list or range and while loops when the number of repeats is unknown.
- Always set a clear stopping condition in while loops to avoid infinite loops.
- Keep loops simple by reducing extra calculations inside them.
- Use list comprehensions to write shorter and faster loops when creating new lists.
- Try enumerate() instead of a manual counter when looping with an index.
- Use break and continue only when necessary to keep the code easy to follow.
- For large data, use generator expressions to save memory and run loops efficiently.
FAQs on Loops in Python
1. What are loops in Python?
Loops in Python allow executing a block of code multiple times until a condition is met. The two main types are for loops and while loops.
2. What is the difference between for and while loops?
- A for loop iterates over a sequence (like a list, tuple, or string) and runs for a fixed number of times.
- A while loop runs as long as a specified condition is True.
3. How do I exit a loop early in Python?
You can use the break statement to immediately stop a loop when a certain condition is met.
4. What is the purpose of the continue statement?
The continue statement skips the current iteration and moves to the next one, without exiting the loop entirely.
5. Can loops be nested in Python?
Yes, you can place one loop inside another. This is useful for working with multi-dimensional data, like nested lists.
6. How can I make loops more efficient?
Avoid unnecessary calculations inside loops, use list comprehensions when possible, and prefer generator expressions for handling large data sets.
7. What is an infinite loop in Python?
An infinite loop occurs when the loop condition always evaluates to True, causing the loop to run indefinitely.
Example:
while True: print("This is an infinite loop")
To stop it, press Ctrl + C or close the program.
Key Points to Remember
Here is the list of key points we need to remember about “Loops in Python”.
- Python has for loops for iterating over sequences like lists and strings, and while loops that run as long as a condition is true.
- Three special statements help control loops: break exits the loop immediately, continue skips the current iteration and moves to the next one, and pass is a placeholder that does nothing.
- Loops can go through lists, tuples, dictionaries, and even strings. Just use “for item in collection:” to access elements easily.
- You can put a loop inside another loop, but be careful—too many nested loops can slow things down.
- If you know exactly how many times to loop, use for. If the loop depends on a condition that could change, use while.
- Always make sure your while loop has a condition that eventually turns False, or your program might keep running forever.
- Keep loops simple, use enumerate() when you need an index, and try list comprehensions for cleaner, faster looping when creating new lists.