Keywords Flashcards
Name four scenarios where as
keyword is used.
- To create an alias for module name in import statement.
- To create an alias for sub-module name in import statement.
- To create an alias for resource in with resource statement.
- To create an alias for exception.
What’s the syntax for creating an alias for exception with as
keyword?
except <exception_name> as <alias_name>
Does assert
throw an error when the following condition is true or false?
When the condition is false.
What’s the syntax for assert
in python?
assert condition, message
What’s the purpose of the del
keyword in python?
del
is used to delete the reference to an object. Ex:
>>> a = b = 5 >>> del a >>> a Traceback (most recent call last): File "<string>", line 301, in runcode File "<interactive input>", line 1, in <module> NameError: name 'a' is not defined >>> b 5
What’s the syntax for try except blocks in python?
try: # Some code except <Exception>: # Run on <Exception> except: # It's possible to put more than one except block under one try # block, and you don't need to specify the <Exception> after the # except keyword
What’s the syntax for the raise
keyword in python?
if num == 0: raise ZeroDivisionError('cannot divide')
What’s the purpose of the finally
keyword?
finally
is used with try…except block to close up resources or file streams.
Using finally
ensures that the block of code inside it gets executed even if there is an unhandled exception.
What are the two uses for the global
keyword?
- To create a global variable inside a function
- To modify a global variable inside a function
What’s the use of the in
and not in
keywords?
in
is used to test if a sequence (list, tuple, string etc.) contains a value. It returns True
if the value is present, else it returns False
. not in
works equivalently.
Can in
and not in
only be used with sequence data structures like lists or sets?
No, it can also be used with generators like range()
What’s the use of the is
keyword in python?
is
is used in Python for testing object identity. While the == operator is used to test if two variables are equal or not, is
is used to test if the two variables refer to the same object.
What’s the syntax for an anonymous function in python?
lambda a: a**2
What’s the difference between the nonlocal
keyword and the global
keyword?
The difference is that the nonlocal
keyword is used only with variables outside the local scope, like for example variables declared in outer function, but not with global variables.
What’s the syntax for the with
statement?
with expression as target_var: do_something(target_var)