In this tutorial, we will learn how to use a for loop in python and types with examples.
Python for loops is used to iterate over a sequence (such as a list, tuple, or string) or other iterate object and execute a block of code for each item in the sequence. This can be a very powerful tool for performing tasks on data and is a crucial part of programming in Python.
If I am printing or executing multiple lines of data, we can use a loop.It's super easy to print. And
There are two types of loops in python:
- for loop
- while loop
Python for loop:
To use a for loop in Python, you use the following syntax:
for item in sequence:
# code to be executed for each item
Here, the above runs a block of code a certain number of times. Each item of the sequence on each iteration is loop continuously until reaching the last item in the sequence.
Read also : student registration form a python with database
Python loop list:
Here's an example of a for loop that iterates over a list of numbers and prints each one to the console:
country = ['India', 'china', 'Sweden', 'Netherland', 'Russia', 'America']
for countries in country:
print(countries)
Output:
India
china
sweden
Netherland
Russia
America
In the above examples, we have to create a list called country. and you want to print out each countries in the list.
using of for loop, we created an array and print the statement first print 'India' and then executed again the way until the last element of an array 'America' the for loop is end.
Python for loop with python range():
You can also use the 'range()' function to create a sequence of numbers to iterate over. For example, the following for loop will print the country from 0 to 4:
country = ['India', 'china', 'Sweden', 'Netherland', 'Russia', 'America']
for i in range(4):
print(country[i])
Output:
India
China
Sweden
Netherland
You can also specify a start and end value for the range() function, like this:
country = ['India', 'china', 'Sweden', 'Netherland', 'Russia', 'America']
for i in range(1, 5):
print(country[i])
Output:
China
Sweden
Netherland
Russia
Finally, you can use the 'enumerate()' function to iterate over a sequence and also get the index of each item. This can be useful if you want to perform some action on each item based on its position in the list.
For Example:
country = ['India', 'china', 'Sweden', 'Netherland', 'Russia', 'America']
for i, countries in enumerate(country):
print(i, countries)
Output:
0 India
1 china
2 Sweden
3 Netherland
4 Russia
5 America
I hope you will learn this helps give you a basic understanding of Python for loops.