Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

In Python, a for loop is used to iterate over a sequence of elements, such as a list, tuple, string, or

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

yamlCopy code
for variable in sequence: # code to be executed

In this syntax, variable is a variable that takes on the value of each element in sequence , and the
indented block of code below the for statement is executed for each value of variable.

Here is an example of a for loop that iterates over a list of numbers and prints each number:

cssCopy code
numbers = [1, 2, 3, 4, 5] for num in numbers: print (num)

In this code, the for loop iterates over the list numbers, and the variable num takes on the value of each
element in the list. The print statement inside the loop prints each value of num .

You can also use the range() function to generate a sequence of numbers that can be used with a for
loop. The range() function takes one, two, or three arguments to define the start, stop, and step size of
the sequence. Here is an example of a for loop that uses range() to iterate over a sequence of
numbers:

You might also like