Python For Loop Basics

Python's for loop allows you to iterate over a sequence of elements, such as a list or a string. This is a convenient way to perform a specific action on each element of the sequence.

Here's the basic syntax for a for loop in Python:

for element in sequence: code block

The code block inside the for loop will execute once for each element in the sequence. The variable element will take on the value of each element in turn, allowing you to perform an action on it within the loop.

Here's an example of a simple for loop that iterates over a list of numbers:

for number in [1, 2, 3, 4, 5]: print(number)

This loop will print the numbers 1 through 5 to the console. The for loop will iterate over each element in the list, assigning the value of each element to the variable number in turn. The code block inside the loop will then execute, printing the value of number to the console.

You can also use the range() function to create a sequence of numbers to iterate over. For example:

for number in range(1, 6): print(number)

This will produce the same output as the previous example. The range() function generates a sequence of numbers from the starting value (in this case, 1) up to, but not including, the ending value (in this case, 6).

You can also use the enumerate() function to iterate over a sequence and access both the index and the value of each element. For example:

words = ['cat', 'dog', 'bird'] for index, word in enumerate(words): print(f'{index}: {word}')

This will print the following output:

0: cat 1: dog 2: bird

The enumerate() function returns a tuple containing the index and value of each element, which are then unpacked into the index and word variables in the for loop.

You can use the break and continue statements within a for loop just as you can with a while loop. The break statement will immediately exit the loop, while continue will skip the rest of the current iteration and move on to the next element.

Overall, the for loop is a powerful and convenient tool in Python for iterating over a sequence of elements and performing a specific action on each one. Whether you're working with a list, a string, or a range of numbers, the for loop can help you accomplish your task efficiently.


No comments

Powered by Blogger.