For Loop In Python

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 40:- For Loop In Python

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. The for loop in Python is versatile and can be used with various types of sequences, including lists, tuples, strings, dictionaries, and even with the range() 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 list fruits, and in each iteration, the variable fruit 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 string text, and in each iteration, the variable char 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 the range() function, and in each iteration, the variable num 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.

6. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?