Loops In Python

Loops are used to run repeated statements. If you want to print 1 to 10 numbers then without loop you have to write Ten statements to print these numbers while with the loop you can do the same task with two lines. There are two types of loops used in Python

FOR Loop

FOR loop is used when you want to run loop for the exact number of iterations. For example, you want to print 1 to 10 alphabets then you know 10 times loop needs to run to print numbers so here for loop should be used for that task. You can also use For loop to iterating sequences such as string or list.

WHILE Loop

WHILE loop is used if you do not know specific number of iterations. It will run still specified condition is satisfied. For Example, you want to print numbers only less than 10 then you will use condition in while loop which satisfies the said statement when the condition false the loop will be automatically terminated.


# print number 1 to 10
print(1)
print(2)
print(3)
print(4)
print(5)
print(6)
print(7)
print(8)
print(9)
print(10)

# print number  1 to 10 with For Loop
for i in range(1,11):
    print(i)

# print number between 1 and 10 with While Loop
i=1
while i<10:
    print(i)
    i = i+1

# table 2 with for loop
for num in range(1,11):
    print(str(num)+"x"+"2= "+str(num*2))

# table 2 with while loop
num = 1
while num<=10:
    print(str(num)+"x"+"2= "+str(num*2))
    num = num+1
Github:
https://github.com/asadraza825/python/blob/master/loops.ipynb
Tags: Python, Python Programming,  Python Loops, For Loop, While Loop
Next Post Previous Post
No Comment
Add Comment
comment url