for i in range(3):
print(i)
else:
print(‘Else block!’)
Show Answer
0
1
2
Else block!
Show Reason
Python loops have an extra feature that is not available in most other programming languages: you can put an else block immediately after a loop’s repeated interior block. The Else block executes when the loop is not terminated by a break block.
def func():
try:
return 42
finally:
print(42)
print(func())
Show Answer
42 will be printed twice.
Show Reason
finally block will run no matter what happens in the try-block. if try block raises a error, encounter a break, continue or return statement then finally block will run.
def func():
try:
return 42
finally:
return 69
Show Answer
69
Show Reason
If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement
try:
import sys
sys.exit()
except:
print("42 is the answer to life.")
Show Answer
42 is the answer to life.
is printed to the screen
Show Reason
The exit() function raises SystemExit Exception which exits the program but since it is placed in a try block this exception is caught and the code in except block runs.
print('abc'.replace('', '|'))
print("".replace("", "advik"))
print("".replace("", "advik", 4))
Show Answer
|a|b|c|
advik
Show Reason
In the first all the empty strings (empty space between letters) is replaced by "|"
In the second one empty string is replace by "advik"
actually a bug which was fixed in the latest version of python. more details here: https://bugs.python.org/issue28029
bad = 'python2'
print('python2' is bad)
bad = 'python3!'
print('python3!' is bad)
Show Answer
True
False