Loops: For and While
Lesson 7: Loops: For and While
Learning Objectives
In this lesson, you will learn:
- What loops are and why they are useful in programming.
- The structure and usage of for loops in Python.
- The structure and usage of while loops in Python.
- How to control loop execution with break and continue statements.
- Common mistakes to avoid when using loops.
- Best practices for writing efficient loops.
Introduction to Loops
Loops are fundamental programming constructs that allow you to execute a block of code repeatedly. This is particularly useful when you want to perform the same action multiple times without rewriting the code. Imagine you are baking cookies and need to mix the ingredients. Instead of writing out the mixing instructions for each batch, you can simply say, "Mix the ingredients 10 times." This is the essence of loops in programming.
The for Loop
The for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects. The syntax of a for loop is as follows:
for variable in iterable:
# code to execute
Here, variable takes the value of each item in the iterable one by one, and the code block inside the loop is executed for each item.
Example of a for Loop
Let’s look at a simple example where we print each fruit in a list:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
In this example, the for loop iterates over the fruits list. The fruit variable takes on the value of each item in the list during each iteration, and the print(fruit) statement outputs each fruit to the console.
The while Loop
The while loop is used to repeat a block of code as long as a specified condition is True. The syntax is as follows:
while condition:
# code to execute
In this case, the condition is evaluated before each iteration, and if it is True, the code block inside the loop is executed.
Example of a while Loop
Here’s an example where we print numbers from 1 to 5 using a while loop:
count = 1
while count <= 5:
print(count)
count += 1
In this example, the while loop continues to execute as long as count is less than or equal to 5. The print(count) statement outputs the current value of count, and count += 1 increments the value of count by 1 after each iteration.
Controlling Loop Execution
Sometimes, you may want to exit a loop prematurely or skip certain iterations. Python provides two statements for this purpose: break and continue.
The break Statement
The break statement is used to exit a loop immediately, regardless of the loop's condition. Here’s an example:
for num in range(10):
if num == 5:
break
print(num)
In this case, the loop will print numbers from 0 to 4. When num equals 5, the break statement is executed, and the loop terminates.
The continue Statement
The continue statement is used to skip the current iteration and move to the next one. Here’s an example:
for num in range(5):
if num == 2:
continue
print(num)
In this case, the loop will print numbers 0, 1, 3, and 4. When num equals 2, the continue statement is executed, and the loop skips the print(num) statement for that iteration.
Common Mistakes to Avoid
- Infinite Loops: A common mistake when using
whileloops is creating an infinite loop, where the condition never becomesFalse. Always ensure that the loop's condition will eventually be met.
python
count = 1
while count <= 5:
print(count)
# Missing count += 1
In this example, count never increases, leading to an infinite loop.
-
Incorrect Indentation: Python relies on indentation to define code blocks. Ensure that all code inside the loop is properly indented. Failure to do so can lead to unexpected behavior.
-
Modifying the Iterable Inside a Loop: Modifying a list while iterating over it can lead to unexpected results. If you need to modify a list, consider creating a copy of it or using list comprehensions.
Best Practices
- Use
forloops when you know the number of iterations in advance or when iterating over a collection. - Use
whileloops when the number of iterations is not known beforehand and depends on a condition. - Limit the scope of your loop variables to avoid conflicts with other parts of your code.
- Always ensure your loops have a clear exit condition to avoid infinite loops.
- Use descriptive variable names to enhance code readability.
Key Takeaways
- Loops are essential for repeating actions in programming.
- The
forloop is used for iterating over sequences, while thewhileloop continues until a condition is met. - Control loop execution with
breakto exit andcontinueto skip iterations. - Be mindful of common pitfalls like infinite loops and incorrect indentation.
Conclusion
In this lesson, you learned how to use loops in Python to repeat actions efficiently. You now understand how to implement both for and while loops, as well as how to control their execution. This foundational knowledge will be instrumental as you progress to the next lesson on functions, where you'll learn how to create reusable blocks of code to further enhance your programming skills.
Exercises
- Exercise 1: Write a
forloop that prints the numbers from 1 to 10. - Exercise 2: Create a
whileloop that prints the even numbers between 1 and 20. - Exercise 3: Modify the
whileloop from Exercise 2 to skip the number 10 using thecontinuestatement. - Exercise 4: Write a program that uses a
forloop to sum all the numbers in a list and print the result. - Practical Assignment: Create a mini-project that asks the user to input a number and then uses a loop to calculate the factorial of that number. Ensure to handle invalid inputs gracefully.
Summary
- Loops allow you to execute a block of code multiple times.
- The
forloop iterates over a sequence, while thewhileloop continues until a condition is false. - Use
breakto exit a loop andcontinueto skip to the next iteration. - Avoid common mistakes like infinite loops and incorrect indentation.
- Writing clear and efficient loops is crucial for effective programming.