Loops in Python with Examples: for and while

Python Basics

Python is a very powerful and widely used programming language that offers various control structures to manage the flow of your code. Among these, loops are essential for executing a block of code repeatedly until a certain condition is met. In this article, we will look at two types of loops in Python: for loop and while loop.

Table of Contents

For Loop Base Structure

The for loop is used when you want to iterate over a sequence (like a list, tuple or string) or other iterable objects. The basic syntax for a for loop is as follows:

for variable in iterable:
    # code block to be executed

Iterating over a range of numbers

for number in range(1, 8):

In this example, we use the range() function as our iterable. It generates a sequence of numbers starting from the first argument (1) and ending before the second argument (8). The variable number takes on each value in the sequence during each iteration.

Iterating over dictionary keys or values

custom_dict = {30: "thirty", 10: "ten",20: "twenty"}
for key in custom_dict:
    print(f"Key: {key}, Value: {my_dict[key]}")
# Or to iterate over values
for value in custom_dict.values():

This example first iterates through the keys of custom_dict, then accesses and prints their corresponding values. The second for loop iterates directly over the dictionary’s values.

Iterating over string characters

custom_string = "Python Coding"
for char in custom_string:

This example iterates through each character in the custom_string, prints it.

While Loop Base Structure

while condition:
    # code block to be executed

While loop

Here’s an example of using a while loop to print the numbers from 1 to 5:

i = 1
while i <= 8:
    i += 1

In this example, we initialize a variable i with the value 1. The condition i <= 8 is checked at the beginning of each iteration. As long as it’s true, the code block inside the loop is executed. After printing the number, we increment the variable i by 1 to continue the loop until the condition becomes false (when i > 8).

Calculating factorial

num = 10
result = 1
while num > 1:
    result *= num
    num -= 1
print(f"The factorial of {num} is:", result)

In this example, we define a number 10. The while loop iterates from the defined number to 0 and multiplies each number with the result variable. This calculation results in the factorial of the given number.

To top