loops in python

Save (0)
Close

Recommended

Description

In Python, a loop is a control flow statement that allows you to execute a block of code repeatedly until a certain condition is met. Python supports two types of loops: while loop and for loop.

1) While loop –
The while loop repeatedly executes a block of code as long as the given condition is True. The structure of a while loop in Python is as follows:

while condition:
statement(s)

– The while loop starts by evaluating the condition. If the condition is True, the loop body is executed, otherwise the loop is terminated. It is important to ensure that the condition eventually becomes False, otherwise the loop will run indefinitely and cause a program to crash.

Example:
# Print numbers from 1 to 5 using a while loop

i = 1
while i <= 5:
print(i)
i += 1

– The output will be:
1
2
3
4
5

2) For loop –
The for loop is another kind of loop in Python which is used to iterate over a sequence of elements, such as a List, Tuple, or a String. The syntax of the for loop is as follows:

for variable in sequence:
statement(s)

– The for loop iterates over each element in the sequence and assigns it to the variable. The statements inside the loop body are executed once for each element in the sequence.

Example:
# Print each character in the word “Python” using a for loop

for c in “Python”:
print(c)

– The output will be:
P
y
t
h
o
n

– In addition to the while and for loops, Python also provides several built-in functions such as range() and enumerate() which are commonly used in loops.

Range() function:
The range() function is used to generate a sequence of numbers. It takes three arguments: start, stop, and step. The start argument is the starting number of sequence (inclusive), stop argument is the ending number of sequence (exclusive), and step argument is the difference between each number in the sequence.

Example:
# Print all even numbers between 0 and 10 using range() function

for i in range(0, 10, 2):
print(i)

– The output will be:
0
2
4
6
8

Enumerate() function:
The enumerate() function is used to iterate over a sequence and keep track of the current index of an element.

Example:
# Print index and element of each item in a list using enumerate() function

fruits = [‘apple’, ‘banana’, ‘mango’, ‘orange’]
for i, fruit in enumerate(fruits):
print(i, fruit)

– The output will be:
0 apple
1 banana
2 mango
3 orange

In conclusion, loops are essential programming constructs in Python that provide a flexible and effective way to automate repetitive tasks and process large amounts of data in a program with ease