For loops are used for sequential traversal.
For loop has two forms:-
1.) for var in list:
statement 1
statement 2
2.) for var in list:
statement 1
statement 2
else:
statement 3
statement 4
- During each iteration var is assigned the next value from the list.
- else block is executed when items in the list get exhauted.
- A for loop can be used to generate a list of numbers using the built-in range() functions.
- range(10)--> Generates numbers from 0 to 9.
- range(10,20)--> Generates numbers from 10 to 19.
- range(10,20,2)--> Generates numbers from 10 to 19 in steps of 2.
- range(20,10,-3)--> Generates numbers from 20 to 11 in steps of -3.
Program 1:Write a program to print the 10 numbers in python.
i=0
num=10
for i in range(i,num):
print(i)
Output:-
i=1
num=int(input("enter the number:\n"))
for i in range(0,num):
print(i,end="")
Output:-
i=2
num=20
for i in range(0,num,2):
print(i)
Output:-
Nested for loop in python:-
- Python allows us to use nested for loop inside your python program.
- The inner for loop is executed first where for every iteration of the outer for loop.
Syntax:-
for var1 in list1:
for var2 in list2:
statement 1
statement 2
statement 3
statement 4
Program 4:Write a program to print the star(*) triangle in python.
i=0
j=0
num=int(input("Enter the number of row which you want to print: \n"))
for i in range(0,num):
print(" ")
for j in range(0,i+1):
print("*", end=" ")
Output:-
How to use else statement in for loop?:-
- Python allows us to use the else statement with the for loop.
- This else statement will be executed only when all the iterations are exhausted.
- If for loop contains break statement then the else statement will not be executed.
Program 5:Write a program to print the natural numbers in decreasing order in python.
i=0
num=int(input("Enter the number:\n"))
for i in range(num,0,-2):
print(i,end=" ")
else:
print("else statement is running")
Output:-
Program 6:Write a program to print the natural numbers in increasing order using break statement in python.
i=0
num=int(input("Enter the number:\n"))
for i in range(0,num,2):
print(i,end=" ")
if(i==8):
break
else:
print("else statement is running")
Output:-
- How to make registration and login page in asp.net using c#
- How to draw flow chart of any algorithms.
- How to install python setup in windows,linux and mac os easily
- How to buy and sell your project easily
- How to know about print function in python in details
- Basic fundamentals of python part 4 in details
- How to create setup file and install on your computer easily
Watch complete Lecture Video:-
0 comments:
Post a Comment