Python For Loop: Title: Excerpt: in A Programming Language, Loops Have Been A Very Necessary Component As It Used For
Python For Loop: Title: Excerpt: in A Programming Language, Loops Have Been A Very Necessary Component As It Used For
Excerpt: In a programming language, loops have been a very necessary component as it used for
different functions. Like any other programming language, Python has loops as well, such as for
loop, which is beneficial for performing iterative tasks. Read on and learn more about for loop in
Python, provided examples.
Permalink: Python_for_loop
Category: python
Syntax
The for loop is declared by using the for keyword. The syntax of the for loop is as follows:
for iterator_variable in sequence:
statement(s) or body of for loop
The iterator_variable is used to iterate through the sequence. The value of the item is taken from
the sequence, and the operation is performed. The for loop doesn’t terminate unless the
last item in the sequence is traversed. The indentation is used to separate the body of for
loop from its declaration.
Now, let’s see the examples of for loops in Python.
In the given example, the current iteration is skipped when the value of the iterator is equal to the
cat.
Using range() function in for loop
The range() function generates the numbers in sequence. We can specify the start, stop, and step
size value within the range function. If the step size value is not defined, then it is 1 by default.
The range() function is also used to access the indexes of the declared sequence. Let’s just take a
look at the examples of the range function. We are writing the simplest program, which uses the
range function to print the number 10. The range() function prints the number from 0 to 9.
#using the range function with the for loop
for num in range(10):
#printing the value of num
print(num)
Output
Now, let’s use start, stop, and step size value with range() function.
#using the range function with the for loop
#the start value is 1, the stop value is 30, and the step value is 3.
for num in range(1,30,3):
#printing the value of num
print(num)
Output
The range() function is also used to the get the indexes of the sequence. Let’s see an example of
this where the len() function is used to return the list’s length.
#declaring a list of animals
animal= ["cow","dog","cat","camel","lion"]
#declaring a for loop
#x is the iterator variable
#getting the length of animal list by using the len() function
for x in range(len(animal)):
#printing each item of the list
print(animal[x])
Output
Conclusion
This article explains the use of for loop in Python with the help of simple examples. The for loop
is used to iterate the container and access the items of the container. This article will be
beneficial for beginners.