New to Programming? No Worries! Start Learning Python from Scratch — Part 3 : Mastering Python Loops
Loops are a fundamental concept in Python, enabling you to automate repetitive tasks and handle data efficiently. With `for` and `while` loops, you can iterate over collections, repeat actions until conditions are met, and significantly reduce code complexity. Mastering loops allows you to write more efficient and elegant Python code, making your programming tasks easier and more powerful.
For Loop
The for
loop in Python is used to iterate over elements in a sequence, such as a list, and perform actions on each element.
Here’s a block of code to sum numbers in a list using a for
loop:
numbers = [1, 2, 3, 4, 5] # List of numbers to be summed
total_sum = 0 # Initialize the sum variable
for num in numbers: # Loop through each number in the list
total_sum += num # Add the current number to the total sum
# After the loop, total_sum contains the sum of all numbers
While Loop
As mentioned above, we use a `for` loop when we know beforehand how many times we want to repeat a block of code. It’s great for iterating over items in a list, a range of numbers, or any sequence where the number of iterations is fixed.
But what about when we do not know beforehand?
The `while` loop is used when we do not know in advance how many times the loop should run. Instead of iterating over a fixed sequence, the `while` loop continues running as long as a certain condition is true. This makes it ideal for situations where we need the loop to continue until something specific happens, like waiting for a user to input a negative number to stop the loop.
Here’s a program that uses a while
loop to continuously ask the user for a number and adds it to a sum until the user enters a negative number:
total_sum = 0
# Start with zero as the total sum
number = int(input("Enter a number (negative to stop): "))
# Get the first number
while number >= 0:
# Continue as long as the number is not negative
total_sum += number
# Add the current number to the total sum
number = int(input("Enter another number (negative to stop): "))
# Get the next number
# Now, total_sum contains the sum of all the positive numbers you entered
Controlling Loop Execution with `break` and `continue`
The break
and continue
statements in Python are used to control the flow of loops. The break
statement is used to exit the loop entirely when a certain condition is met, while the continue
statement skips the rest of the code inside the loop for the current iteration and moves on to the next iteration.
continue
in PythonHere’s an example of how both break
and continue
work:
for number in range(1, 10):
if number == 5:
break # Exit the loop when number is 5
if number % 2 == 0:
continue # Skip the rest of the loop if number is even
print(number)
Explanation Of The Above Code
The loop starts by iterating over numbers from 1 to 9.
For each number:
- If the number is
5
, thebreak
statement is triggered, and the loop exits immediately, so no further numbers are processed. - If the number is even (like
2
,4
), thecontinue
statement is triggered, which skips theprint
statement for that iteration and moves to the next number. - If the number is odd and not
5
, it gets printed.
So, the numbers 1
and 3
are printed before the loop reaches 5
and breaks, stopping further execution.