Else with loop in python
Else With Loop
The else clause executes after the loop completes
normally. This means that the loop did not encounter a break statement. यदि loop अपने आप terminate हो रहा रहा है या एक बार भी नहीं चल रहा है तो else चलेगा
ओर यदि break से terminate होता है तो loop
नहीं चलेगा।
Else in For Loop
The else keyword
in a for loop specifies a block of code to be executed when the loop
is finished:
Example
Print
all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally
finished!")
Note: The else block
will NOT be executed if the loop is stopped by a break statement.
Example
Break
the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x
== 3: break
print(x)
else:
print("Finally
finished!")
Else in While Loop
With the else statement
we can run a block of code once when the condition no longer is true:
Example
Print
a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i
is no longer less than 6")
Example
i = 1
while i < 6:
print(i)
if
i == 3: break
i += 1
else:
print("i
is no longer less than 6")
Post a Comment