Control flow is a fundamental concept in programming that allows developers to control the order of execution of statements in their code. In Python, there are several constructs that allow you to implement control flow, with loops being one of the most commonly used. In this beginner's guide to Python loops, we will explore how to use loops to iterate over sequences, perform repeated actions, and more.
What are Loops?
Loops are constructs in programming that allow you to repeat a set of instructions multiple times. In Python, there are two types of loops: for
loops and while
loops. Both loops allow you to execute a block of code repeatedly, but they differ in how they control the number of iterations.
The for
Loop
The for
loop is used to iterate over a sequence of items. A sequence can be any collection of items, including lists, tuples, and strings. The basic syntax of a for
loop is as follows:
for item in sequence:
# do something with item
The for
loop starts by initializing a variable item
to the first item in the sequence. It then executes the block of code inside the loop, which can access the current value of item
and perform some action on it. After the block of code is executed, the loop moves on to the next item in the sequence and repeats the process until all items have been processed.
Let's look at an example of a for
loop that iterates over a list of numbers and prints out each number:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
Output:
1
2
3
4
5
In this example, the for
loop iterates over the list of numbers, and for each number, it prints out the value of the variable number
. The loop continues until all items in the list have been processed.
The range()
Function
In some cases, you may need to execute a block of code a specific number of times, rather than iterating over a sequence of items. In such cases, you can use the range()
function to generate a sequence of numbers that can be used in a for
loop.The range()
function takes one, two, or three arguments, depending on how you want to use it. The basic syntax is as follows:
range(stop)
range(start, stop)
range(start, stop, step)
The range()
function generates a sequence of numbers that starts at start
, ends at stop
(exclusive), and increments by step
(default is 1). Here are some examples:
# generate a sequence of numbers from 0 to 4 (exclusive)
for i in range(5):
print(i)
# generate a sequence of numbers from 2 to 5 (exclusive)
for i in range(2, 5):
print(i)
# generate a sequence of numbers from 0 to 10 (exclusive), incrementing by 2
for i in range(0, 10, 2):
print(i)
Output:
0
1
2
3
4
2
3
4
0
2
4
6
8
The while
Loop
The while
loop is used to execute a block of code repeatedly as long as a certain condition is true. The basic syntax of a while
loop is as follows:
while condition:
# do something
The while
loop starts by checking the condition. If the condition is true, the loop executes the block of code inside it. After the block of code is executed, the condition is checked again. If it is still true, the block of code is executed again, and the process repeats until the condition becomes false.
Let's look at an example of a while
loop that counts down from 5 to 1:
count = 5
while count > 0:
print(count)
count -= 1
Output:
5
4
3
2
1
In this example, the while
loop executes as long as the value of count
is greater than 0. Each time the loop iterates, it prints the current value of count
and subtracts 1 from it, until count
becomes 0 and the loop exits.
Loop Control Statements
In addition to for
and while
loops, Python also provides loop control statements that allow you to modify the behavior of loops.
The break
Statement
The break
statement is used to exit a loop prematurely. When a break
statement is executed inside a loop, the loop immediately exits, and the program continues with the next statement outside the loop.
Let's look at an example of using the break
statement in a for
loop that searches for a specific value in a list:
numbers = [1, 2, 3, 4, 5]
search_value = 3
for number in numbers:
if number == search_value:
print("Found it!")
break
print("Loop finished")
Output:
Found it!
Loop finished
In this example, the for
loop iterates over the list of numbers and checks each number to see if it matches the search value. When it finds the value, it prints "Found it!" and exits the loop using the break
statement. The program then continues with the next statement outside the loop, which prints "Loop finished".
The continue
Statement
The continue
statement is used to skip the rest of the current iteration of a loop and move on to the next iteration. When a continue
statement is executed inside a loop, the loop immediately jumps to the next iteration, skipping any code that comes after the continue
statement for the current iteration.
Let's look at an example of using the continue
statement in a for
loop that skips even numbers:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number % 2 == 0:
continue
print(number)
Output:
1
3
5
In this example, the for
loop iterates over the list of numbers and checks each number to see if it is even. If the number is even, the continue
statement is executed, and the loop skips to the next iteration without printing anything. If the number is odd, the loop prints the number using the print()
statement.
The else
Clause
In Python, loops can also have an optional else
clause that is executed when the loop completes normally (i.e., without a break
statement being executed). The else
clause is placed after the loop block and contains code that should be executed after the loop completes.
Let's look at an example of using the else
clause in a for
loop that searches for a specific value in a list:
numbers = [1, 2, 3, 4, 5]
search_value = 6
for number in numbers:
if number == search_value:
print("Found it!")
break
else:
print("Not found")
print("Loop finished")
Output:
Not found
Loop finished
In this example, the `for` loop iterates over the list of numbers and checks each number to see if it matches the search value. When it finds the value, it prints "Found it!" and exits the loop using the `break` statement. If the loop completes without finding the value, the `else` clause is executed, which prints "Not found". The program then continues with the next statement outside the loop, which prints "Loop finished".
Conclusion
In this beginner's guide to Python loops, we covered the basics of using `for` and `while` loops to iterate over sequences of values and execute blocks of code repeatedly. We also learned about loop control statements like `break` and `continue`, which allow us to modify the behavior of loops, and the `else` clause, which can be used to execute code after a loop completes normally. By mastering control flow in Python, you'll be able to write more complex programs that can solve a wide variety of problems.