Exercise: Python

Questions for: Conditional Statements

How can you check if a key exists in a dictionary?
A:
Using if key in dict
B:
Using if exists(dict[key])
C:
Using if contains(dict, key)
D:
Using if key: dict
Answer: A
The in keyword is used to check if a key exists in a dictionary in Python.
Which of the following is the correct way to handle multiple exceptions in a try-except block?
A:
try:
    # code block
except Exception1:
    # handle Exception1
except Exception2:
    # handle Exception2
B:
try:
    # code block
except Exception1, Exception2:
    # handle exceptions
C:
try:
    # code block
except (Exception1, Exception2):
    # handle exceptions
D:
try:
    # code block
catch Exception1:
    # handle Exception1
catch Exception2:
    # handle Exception2
Answer: C
The correct syntax is to use a tuple in the except clause to handle multiple exceptions.
What will be the output of the following code?
num = 0
if num:
    print("Non-zero")
else:
    print("Zero")
A:
Non-zero
B:
Zero
C:
Error
D:
No output
Answer: B
The condition if num checks if num is truthy. Since num is 0, which is falsy, the code inside the else block is executed, printing "Zero."
What does the elif statement stand for?
A:
Else If
B:
End Loop If
C:
Execute Last If
D:
Exit Loop If
Answer: A
The elif statement is short for "else if" and is used to check additional conditions after the initial if statement.
Which built-in function is used to check the type of an object?
A:
typeof()
B:
type()
C:
otype()
D:
istypeof()
Answer: B
The type() function is used to check the type of an object in Python.
Ad Slot (Above Pagination)
Quiz