Zone Of Makos

Menu icon

For Loop in Python

The for loop is a fundamental control structure in Python that allows you to iterate over a sequence of values, such as a list or a string. In this tutorial, you'll learn how to use the for loop in Python.

Using the for Loop with Lists

One of the most common ways to use the for loop in Python is to iterate over a list of values. Here's an example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

This code will output:

apple
banana
cherry

Here's what's happening:

  • The for loop starts by assigning the first value in the list to the variable fruit .
  • The print statement outputs the value of fruit .
  • The loop repeats these two steps for each subsequent value in the list.

When the loop has iterated over every value in the list, the loop ends.

Using the for Loop with Strings

You can also use the for loop to iterate over the characters in a string:

name = "John"

for char in name:
    print(char)

This code will output:

J
o
h
n

Here's what's happening:

  • The for loop starts by assigning the first character in the string to the variable char .
  • The print statement outputs the value of char .
  • The loop repeats these two steps for each subsequent character in the string.

When the loop has iterated over every character in the string, the loop ends.

Using the range() Function with for Loops

The range() function is a built-in Python function that generates a sequence of numbers. You can use this function with the for loop to iterate over a sequence of numbers:

for i in range(3):
    print(i)

This code will output:

0
1
2

Here's what's happening:

  • The range() function generates a sequence of numbers from 0 to 2 (inclusive).
  • The for loop iterates over each number in the sequence.
  • The print statement outputs the value of i .

When the loop has iterated over every number in the sequence, the loop ends.

Conclusion

The for loop is a powerful tool for iterating over sequences of values in Python. You can use it with lists, strings, and the range() function to perform a wide range of tasks. With the for loop, you can write code that is both concise and expressive.

Remember that the syntax for the for loop in Python is:

for variable in sequence:
    # code to execute

Where variable is the name of the variable that will hold each value in the sequence, and sequence is the sequence of values to iterate over.

With the knowledge you've gained in this tutorial, you should be able to use the for loop in Python to solve a wide range of programming problems. Happy coding!