For loop in Python
In this tutorial, you will learn about the for loop in python, its syntax and how to use for loop in python with some examples.
Loops in Python
Loops are statements that run until a certain condition is reached. Python supports the following loops.
- While
- For
For loop in Python
The ‘for loops’ in python is generally used for sequential traversing or iterating through a sequence. Using the ‘for loop’ we can execute a set of statements, one for each item in a list, tuple, set etc.
Syntax:
for condition: statements(s)
Now let’s understand the concept of for loop with the help of some programs.
Sample program using for loop to print letters in a string
Input
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1289′,’_blank’)”]
for i in “Developer Publish Academy”: print(i)
Output:
D e v e l o p e r P u b l i s h A c a d e m y
Sample program using for loop to exclude an object from a list
Input
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1290′,’_blank’)”]
alphabets=["a","b","c","d","e",'f',"g","h","i","j","k"] for x in alphabets: if x =="i": continue print(x)
Output:
a b c d e f g h j k
The range() function in python
Now have you learned about ‘for loop’ in python, we will see about the range function and how it can be used with the for loops.
The range() function is an inbuilt function in python. When used in a program, it returns a sequence of numbers starting from zero and increment by one by (default) and finishes at a restricted number.
Syntax:
range
(start, stop, step
)
start- initial value
stop- the final value
step- incrementation value
Sample program using the range () function
Input:
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1291′,’_blank’)”]
for x in range(7): print(x) #this prints all the value from 0-6 for i in range (57, 60): print(i)# this prints the values from 57-59 for j in range (57, 67,2): print(j) #this prints the values from 57-67 with 2 as the incrementation value
Output:
0 1 2 3 4 5 6 57 58 59 57 59 61 63 65