
Python Loops
Loops are fundamental constructs in programming that allow you to execute a block of code repeatedly. In Python, you’ll encounter two main types of loops: for
and while
loops. In this part of our Python crash course, we dive into each type and see how they work.
for
Loops
for
loops are commonly used when you want to iterate over a sequence, such as a list, tuple, string, or range. Here’s the basic syntax of a for
loop in Python:
for variable in sequence:
# Code to execute for each item in the sequence
variable
is a temporary variable that takes on the value of each item in thesequence
.- The code block under the loop is executed for each item in the sequence.
Example: Iterating through a List
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
In this example, the for
loop iterates through the fruits
list and prints each fruit.
while
Loops
while
loops are used when you want to execute a block of code as long as a condition is True
. The syntax of a while
loop is as follows:
while condition: # Code to execute as long as the condition is True
- The code block under the loop is executed repeatedly as long as the
condition
remainsTrue
. - Be careful when using
while
loops to avoid infinite loops.
Example: Countdown with a while
Loop
count = 5 while count > 0: print(count) count -= 1
This while
loop counts down from 5 to 1.
Loop Control Statements
Python provides loop control statements to alter the flow of loops. Two common control statements are:
break
: It allows you to exit a loop prematurely.continue
: It allows you to skip the current iteration and continue to the next one.
Example: Using break
fruits = ["apple", "banana", "cherry"] for fruit in fruits: if fruit == "banana": break print(fruit)
This code will stop the loop as soon as it encounters the “banana” and won’t print “cherry.”
Nested Loops
You can also nest loops inside each other to handle more complex scenarios. For instance, using a for
loop within a for
loop or a while
loop within a for
loop.
Example: Nested for
Loops
for i in range(3): for j in range(2): print(f"({i}, {j})")
This code demonstrates a nested for
loop, which iterates through both i
and j
.
Conclusion
Loops are an integral part of programming and play a crucial role in automating repetitive tasks and handling various data structures. By mastering the use of loops in Python, you’ll be well-equipped to create efficient and dynamic programs.
In the next part of our Python crash course, we’ll explore how to work with Conditional Statements to make decisions in your code. Stay tuned!
That’s All Folks!
You can explore more of our Python guides here: Python Guides