If - Elif - Else Assignment
If - Elif - Else Assignment
Same as that of for loop, we can have an optional else block with while loop as
well.
The else part is executed if the condition in the while loop evaluates to False.
The while loop can be terminated with a break statement. In such case,
the else part is ignored. Hence, a while loop's else part runs if no break occurs and
the condition is false.
counter = 0
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
break statement can be used to stop a for loop. In such case, the else part is ignored.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so
on.
If all the conditions are False, body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks.
Syntax of if...elif...else
if test expression:
Body of if
Body of elif
else:
Body of else
Syntax of pass
pass
pass
In such cases, we may first want to clean up the string and remove all the
punctuation marks. Here is an example of how it is done.
Ex:
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
no_punct = ""
print(no_punct)
Ex:
# import module
import calendar
yy = 2014
mm = 11
EX:
Find ASCII Value of Character
Reference:
https://www.programiz.com/python-programming/looping-technique