What are For Loops in Python - How to Create For Loop in Python Programming

Опубликовано: 13 Октябрь 2024
на канале: Colorstech Training (By Slidescope)
111
6

#dataanalytics #forloop #learnpython

In Python, a for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). It is often used when you have a block of code that you want to repeat a fixed number of times, or when you want to iterate through the elements of a sequence.

The basic syntax of a for loop in Python is as follows:

for variable in sequence:
Code to be executed for each element in the sequence

Here, variable is a variable that takes the value of each element in the sequence during each iteration of the loop.

Let's look at some examples:

Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output:
apple
banana
cherry

Iterating over a range of numbers:
for i in range(5):
print(i)

Output:
0
1
2
3
4

Iterating over a string:
for char in "Hello":
print(char)

Output:
H
e
l
l
o

You can also use the enumerate() function to iterate over both the elements and their indices:

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")

Output:
yaml

Index 0: apple
Index 1: banana
Index 2: cherry

These are just basic examples, and for loops in Python offer a lot of flexibility and can be used in various scenarios.
Learn Python from Experts - https://slidescope.com/python-trainin...