Getting Started with Python — Looping
Looping is an essential part of programming, and it allows you to repeat a block of code multiple times. In Python, there are two types of loops: the for
loop and the while
loop. In this article, we'll cover the basics of looping in Python and provide code examples for each type of loop.
For Loop
A for
loop is used for iterating over a sequence of values. The sequence can be a list, a tuple, a dictionary, a set, or a string. Here's an example of a for
loop:
# loop over a list of numbers
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
# loop over a string
string = "hello"
for character in string:
print(character)
# loop over a range of numbers
for number in range(1, 6):
print(number)
In the first example, we loop over a list of numbers and print each number. In the second example, we loop over a string and print each character. In the third example, we loop over a range of numbers from 1 to 5 and print each number.
While Loop
A while
loop is used to repeatedly execute a block of code as long as a certain condition is true. Here's an example of a while
loop:
# loop while a condition is true
count = 0
while count < 5:
print(count)
count += 1
# loop until a condition is true
count = 0
while True:
print(count)
count += 1
if count == 5:
break
In the first example, we loop while the count
variable is less than 5, and we print the value of count
in each iteration. In the second example, we loop infinitely until the count
variable is equal to 5, at which point we break out of the loop.
Nested Loops
Nested loops are loops that are placed inside another loop. Here’s an example of a nested loop:
# loop over a 2D list
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in grid:
for number in row:
print(number)
In this example, we loop over a 2D list and print each number. The outer loop iterates over the rows of the list, while the inner loop iterates over the numbers in each row.
Conclusion
Looping is a powerful feature in Python, and it allows you to repeat a block of code multiple times. In this article, we covered the basics of looping in Python, including the for
loop, the while
loop, and nested loops. By using loops in your Python programs, you can automate repetitive tasks and make your code more efficient.
Part 7: Getting Started with Python — Functions | by TechwithJulles | Feb, 2023 | Medium
Article Notebook — Google Drive
If you enjoyed this article and would like to show your support, feel free to buy me a coffee! Your support is greatly appreciated and it helps me continue creating content that you love. You can make a contribution by following this link: Buy Me a Coffee. Thank you for your generosity and for being a part of this journey!