Types of for loop
There are two types of loops in Python, for and while. For loops iterate over a
given sequence. While loops repeat as long as a certain boolean condition is met.
Types of Loops
• While
• For
While Loop
While expression:
Statement(s)
Define condition with While Loop.
This will generate output as 0,1,2,3,4,6,7,8,9,10. The loop will terminate when
the condition count < 10 is met, that is up to when count is 9.
Example
count = 0
while count < 10:
print(count)
count += 1 # This is the same as count = count + 1
Result
Define Infinite Loop with While Loop.
Example
count=1;
while count != 0:
count +=1
print (count)
count =input("Enter 0 to quit the loop")
Result
Define While Loop with break and continue statement.
This will generate output as 0,1,2,3,4,5,6,7,8,9, Break statement is used to break
at 10 from loop. Continue at even number and print only odd numbers.
Example
count = 0
while True:
count += 1
if count >= 10:
break
if count % 2 == 0:
continue
print(count)
Result
Define Else in While Loop
This prints out 0,1,2,3,4 and then it prints "count value reached 5". When While
condition is met ,Else statement will execute. Increment the count till count < 5.
Else jump to Else statement.
Example
count=0
while(count< 10):
print(count)
count +=1
else:
print(" End of Loop at %d" %(count))
Using if & Else in While Loop
This will prints out 1,2,3,4
Example
while (count < 10):
if (i%5==0):
break
else:
print( 'Break at %d'%count)
Result
No comments:
Post a Comment