Python For loop

The for loop in Python is used to iterate over a sequence (such as a list, tuple, or string) or other iterable object and execute a block of code for each item in the sequence.

The basic syntax for a for loop is:

for variable in sequence:
# code to execute for each item in the sequence

The variable is a placeholder for the current item in the sequence, and sequence is the sequence you want to iterate over.

Here’s an example of a for loop in Python:

states = [“Alabama”, “Utah”, “Colorado”]
for state in states:
print(state)

In this example, the for loop iterates over the fruits list, and for each item (fruit) in the list, the code inside the loop print(fruit) is executed, and the output is:

Alabama
Utah
Colorado

In summary, the for loop in Python allows you to easily iterate over a sequence or other iterable object and execute a block of code for each item in the sequence.

Disclaimer: The information provided on the blog is for educational and informational purposes only. It should not be considered as a substitute for professional advice.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s