Python else statement
Else statment can be used in:
- if else statment
- loops
- try-except statement
If else statment
- if-else
if random.randint(5, 15) > 10:
print("Randome number was > 10.")
else:
print("Randome number was <= 10.")
Loops
- for-in loop
for i in range(1, random.randint(5, 15)):
if i > 10:
break
print(i)
else:
print("Printed all the numbers!")
- while loop
import random
i = 1
end = random.randint(5, 15)
while i < end:
if i > 10:
break
print(i)
else:
print("Printed all the numbers!")
Try except statement
- try-except
try:
pass
except:
print("Unreachale code!")
else:
print("First print!")
finally:
print("Second print!")
Interview Questions
1. When will else-block be excuted in a loop?
When no break occurs.
2. When will else-block be excuted in a try-except statement?
When no exception occurs.
3. When will else-block be excuted in a try-catch statment - after or before finaly statment?
Before finaly.