If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, a
forloop is used to iterate over a sequence of elements. It allows you to execute a block of code for each item in the sequence. Theforloop 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
forloop in Python is as follows:pythonCopy code
for item in sequence: # Code block to execute for each itemHere's how a
forloop 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 orangeExample 2: Looping over a string:
pythonCopy code
text = "Python" for char in text: print(char)Output:
cssCopy code
P y t h o nExample 3: Looping using the
range()function:pythonCopy code
for num in range(1, 6): print(num)Output:
Copy code
1 2 3 4 5In the first example, the
forloop iterates over the listfruits, and in each iteration, the variablefruittakes the value of each element in the list, and the corresponding code block is executed.In the second example, the
forloop iterates over the stringtext, and in each iteration, the variablechartakes the value of each character in the string, and the corresponding code block is executed.In the third example, the
forloop iterates over the sequence of numbers generated by therange()function, and in each iteration, the variablenumtakes the value of each number in the sequence, and the corresponding code block is executed.The
forloop 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.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support