Skip to content

ADV1K/DoYouKnowPython

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 

Repository files navigation

Do you think you know Python?

What Will be the output? Why?

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.

Reference

https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

What Will happen when you run this code?

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.


What Will be returned when you call the function?

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

Reference

https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions


What Will happen when you run this code?

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.

Reference

https://docs.python.org/3/library/sys.html#sys.exit


What Will Be The Output?

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


What Will Be The Output?

bad = 'python2'
print('python2' is bad)

bad = 'python3!'
print('python3!' is bad)
Show Answer
True
False
Show Reason this is due to string interning.
Reference https://stackabuse.com/guide-to-string-interning-in-python/

About

Do you think you know Python?

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published