If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, a
for
loop is used to iterate over a sequence of elements. It allows you to execute a block of code for each item in the sequence. Thefor
loop in Python is versatile and can be used with various types of sequences, including lists, tuples, strings, dictionaries, and even with therange()
function.The general syntax of a
for
loop in Python is as follows:pythonCopy code
for item in sequence: # Code block to execute for each item
Here's how a
for
loop is typically used:Example 1: Looping over a list:
pythonCopy code
fruits = ["apple", "banana", "orange"] for fruit in fruits: print(fruit)
Output:
Copy code
apple banana orange
Example 2: Looping over a string:
pythonCopy code
text = "Python" for char in text: print(char)
Output:
cssCopy code
P y t h o n
Example 3: Looping using the
range()
function:pythonCopy code
for num in range(1, 6): print(num)
Output:
Copy code
1 2 3 4 5
In the first example, the
for
loop iterates over the listfruits
, and in each iteration, the variablefruit
takes the value of each element in the list, and the corresponding code block is executed.In the second example, the
for
loop iterates over the stringtext
, and in each iteration, the variablechar
takes the value of each character in the string, and the corresponding code block is executed.In the third example, the
for
loop iterates over the sequence of numbers generated by therange()
function, and in each iteration, the variablenum
takes the value of each number in the sequence, and the corresponding code block is executed.The
for
loop is a powerful construct in Python and is widely used to perform tasks that require iterating over a collection of elements or performing a certain action a specific number of times.
Comments: 0