Combine for loops with if statements #
for loops and if statements can be combined to perform more complex operations. A common use case is to loop through a list and perform a specific action based on a condition.
Here's an example of how to use a for loop with an if statement. Note the level of indentation for each code block:
for number in range(10):
if number > 5:
print(number)
Output:
6
7
8
9
In the example above, we loop through numbers from 0 to 9. However, with each iteration, we check that the variable number is greater than 5 to call the print() function, which we can see from the output showing the numbers only from 6 to 9.
Exercise #
- Add an
ifstatement within theforloop so thatmy_numbersonly contains the numbers from 0 to 10.
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules