While Loop
'''
While Loop:
The 'while' loop as the name suggests, execute statements while the condition is True.
As soon as the condition becomes False, the interpreter comes out of the while loop.
'''
for i in range(3):
print(i)
#output = 0
# 1
# 2
i = 0
while(i<3):
print(i)
i = i + 1
#output = 0
# 1
# 2
x = 2
while(x <= 10):
print(x)
x = x + 2
print("Done with the loop")
#output = 2
# 4
# 6
# 8
# 10
# Done with the loop
y =int(input("Enter the number: "))
while(y <= 38):
y = int(input("Enter the number: "))
print(y)
print("Done with the loop")
#Enter the number: 10
#10
#Enter the number: 38
#38
#Enter the number: 100
#Done with the loop
count = 5
while(count > 0):
print(count)
count = count - 1
else:
print("I am inside else")
#output = 5
# 4
# 3
# 2
# 1
#I am inside else
#Here the count variable is set to 5, which decrements after each iteration.
#Depending upon the while loop condition, we need to either increment or decrement the count variable(the variable count, in our case) or the loop will continue forever.
'''
Else with While Loop:
In Python, as soon as the while loop condition becomes false, the interpreter comes out of the while loop and else statement is executed.
'''
count = 1
while count <= 5:
print("This is loop number", count)
count += 1
#output = This is loop number 1
# This is loop number 2
# This is loop number 3
# This is loop number 4
# This is loop number 5
'''
Do-While Loop in Python:
It is a loop in which a set of instructions will execute at least once(irrespective of the condition) and then the repetition of the loop's body will depend on the condition passed at the end of while loop.
'''
Comments
Post a Comment