On the fifth day of learning Python, we will be discussing loops in Python. Loops are used to repeatedly execute a block of code until a certain condition is met. There are two types of loops in Python: for loop and while loop.
The for loop is used to iterate over a sequence of elements. It can be used to iterate over a list, tuple, string, or any other iterable object. The syntax of the for loop is as follows:
for {variable} in {sequence}:
{statements}
Here, {variable} is the variable that takes the value of the next element in the {sequence}.
The {statements} within the loop are executed for each element in the sequence. Let's see an example:
# iterate over a list of numbers
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
# iterate over a string
my_string = "Hello, world!"
for char in my_string:
print(char)
# iterate over a dictionary
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
print(key, my_dict[key])
You can also use the **range()**function to generate a sequence of numbers to iterate over. The basic syntax of range() is as follows:
range(start, stop, step)
# In this structure, start represents the first number in the sequence, stop represents the last number (which is not included in the sequence), and step represents the amount to increment by between each number. If start is omitted, it defaults to 0; if step is omitted, it defaults to 1.# iterate over a range of numbers
for i in range(5):
print(i)
# iterate over a range with a specified start, stop, and step
for i in range(1, 10, 2):
print(i)
The while loop is used to repeatedly execute a block of code until a certain condition is met. The syntax of the while loop is as follows:
while {condition}:
{statements}
Here, {condition} is the condition that is checked at the beginning of each iteration. The {statements} within the loop are executed until the {condition} becomes false. Let's see an example:
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
In this example, the loop continues until the value of i is greater than 5.