Python Loops: For Loops and While Loops - Day 108 of #365DaysOfCode

Day 108 of #365DaysOfCode and Day 8 of #100DaysOfPython & #100DaysOfCode! Today, I dedicated most of my time to catching up on the Python course. In this blog post, I want to share my learning journey with you, specifically focusing on Python for loops. This post is especially for those who are just setting out on their coding journey or those simply wanting to refresh their Python basics.

For loops are a fundamental construct in Python that allow us to iterate over a sequence of elements. They provide a concise and efficient way to perform repetitive tasks or iterate through collections such as lists, tuples, or strings. The structure of a for loop consists of an iteration variable, an iterable, and a block of code to be executed for each iteration.

Syntax:

Iterating over a list:

fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
orange

Using the Range Function:

for number in range(1, 6):
    print(number)

Output:

1
2
3
4
5

For loops are a fundamental construct in Python that allow us to iterate over a sequence of elements. They provide a concise and efficient way to perform repetitive tasks or iterate through collections such as lists, tuples, or strings. With for loops, we specify the iterable and execute a code block for each item in the iterable.

While loops, on the other hand, allow us to repeatedly execute a block of code as long as a specified condition is true. They are useful when the number of iterations is not known beforehand or when we want to continuously repeat an action until a certain condition is met.

count = 5

while count > 0:
    print(count)
    count -= 1

# Output

5
4
3
2
1

By leveraging loops, we can efficiently perform repetitive tasks and process data collections. Hope this was helpful. Happy coding!