All sample questions / Python
What does print(greet(5) if False else greet('5')) print? Python Scope, Functions and Closures
Block 2, Scope, Functions and Closures, question 18 of the Python sample
def greet(name: str) -> str:
return 'hello ' + name
print(greet(5) if False else greet('5'))
What does this print?
Show the answer and why each option is right or wrong
Answer, A. hello 5
- A. hello 5
- Correct. Since the condition is False, only greet('5') actually runs, and because annotations are never enforced, the string '5' is concatenated directly onto 'hello ', producing 'hello 5'.
- B. hello '5'
- Assumes the string argument keeps its quote characters when concatenated, as if it were the code representation of the string rather than its plain text content.
- C. TypeError
- Assumes the str annotation is enforced and that passing a value which does not match it raises an error before the function body runs.
- D. hello 5.0
- Assumes the string argument is somehow converted to a float representation before being concatenated.
A conditional expression only evaluates the branch selected by its condition, the other branch's function call never executes at all. As with any other annotation, the str hint on name has no effect on which argument types are accepted, the function simply concatenates whatever value it receives.
The answer above is what the CPython interpreter printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 600 Python interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 600 Python questions, 9 euros
Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros
Or play the free Python sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.