Python For Loop Examples

htt‮‬ps://www.lautturi.com
Python For Loop Examples

A for loop in Python is used to iterate over a sequence of elements, such as a list, tuple, or string. The syntax for a for loop in Python is:

for variable in sequence:
    # loop body

Here's an example of a simple for loop in Python that iterates over a list of numbers and prints each number:

# Iterate over a list of numbers and print each number
numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)

This will output the following:

1
2
3
4
5

In this example, the for loop iterates over the numbers list, and the loop body is executed for each element in the list. The loop variable number is assigned the value of each element in the list, and the print() function is used to print the value of the loop variable.

You can also use a for loop to iterate over a string and print each character:

# Iterate over a string and print each character
string = "Hello"
for character in string:
    print(character)

This will output the following:

H
e
l
l
o

It's important to note that the loop body is indented, and the indentation determines which statements are part of the loop body. In Python, indentation is important and is used to indicate blocks of code.

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

# Iterate over a range of numbers and print each number
for number in range(1, 6):
    print(number)

This will output the same numbers as the first example.

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

# Iterate over a list and print the index and value of each element
numbers = [1, 2, 3, 4, 5]
for index, number in enumerate(numbers):
    print(f"Index: {index}, Value: {number}")

This will output the following:

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5

You can also use the break and continue statements to control the flow of a for loop. The break statement is used to exit the loop early, and the continue statement is used to skip the remainder of the current iteration and move on to the next iteration.

Consult the Python documentation and online resources for more information on how to use for loops in Python.

Created Time:2017-10-30 14:27:12  Author:lautturi