For Loop in Python
For Loop in Python
Python provide three ways for executing the loop , For loop is one of them. For loops are used for sequential traversal. If we want to iterate over natural numbers , we can make a list of the number or we can use Range keyword.
For Loop in Python
A for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence.
Syntax :
- for iterator_variable in sequence:
- #body of the loop
- Example:
- for i in list/string:
- body of the loop.
- for i in list/string:
Code :
Run
#python program to illustrate for loop list=[1,2,3,4] for i in list: # i will acquire the value's in the list one by one print(i,end=' ') print('') x={'A':1,'B':2} for i in x.keys(): # i will have the values of key of the dictionary print(x[i] , end=' ') print('') # if we want to iterate over natural number from 0 to 5 n=5 for i in range(n+1): # loop will run 6 times for 0 1 2 3 4 5 print(i,end=' ') print('') #for loop from 2 to 5 n=5 for i in range(2,n+1): print(i,end=' ') print('') #loop with incremenation=2 n=12 for i in range(2,n,2): #all the even numbers from 2 to 11 print(i, end=' ') print('') #loop from n to 0 n=5 for i in range(n,-1,-1): # loop from n to -1 (excluding) with rate of -1 (we can change the rate to -2 or -3) print(i,end=' ') print('') #nested for loop for i in range(2): for j in range(2): # loop will rum 2*2 = 4 times print(i , end=' ') print('')
Output: 1 2 3 4 1 2 0 1 2 3 4 5 2 3 4 5 2 4 6 8 10 5 4 3 2 1 0 0 0 1 1
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment