Operators, Comparisons & Short-Circuiting — Concept Check
Questions on Operators, Comparisons & Short-Circuiting. Python operators read like English — and, or, not — with short-circuit evaluation, chained comparisons (0 < x < 10), and identity/membership operators (is, in) that interviews love.
Questions in this quiz
8 questions on Operators, Comparisons & Short-Circuiting — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.A Python script checks if a number is between 1 and 10 using `1 < x < 10`. What does this expression do?
- AIt checks if x is equal to 1 and 10.
- BIt checks if x is either 1 or 10.
- CIt checks if x is greater than 1 and less than 10.
- DIt checks if x is greater than 1 or less than 10.
2.You have a list `nums = [2, 4, 6]`. What is the time complexity of `4 in nums`?
- AO(log n)
- BO(1)
- CO(n^2)
- DO(n)
3.Given `user = None`, what happens when `user and user.save()` is executed?
- ANothing happens as the expression short-circuits.
- BThe variable user is set to a default value.
- CAn AttributeError is raised.
- DThe method save() is called.
4.A developer uses `x or 'default'` to assign a value. What does this expression return if x is an empty string?
- ANone
- B'default'
- Cx
- DAn error is raised
5.Consider the expression `False and loud()`. What is printed?
- AFalse
- BNothing is printed
- CAn error is raised
- D'evaluated!'
6.In Python, what does `7 in {3, 7, 1}` return and why?
- ATrue, because membership in a set is O(1) on average.
- BFalse, because 7 is not the first element.
- CTrue, because it checks all elements like a list.
- DFalse, because sets do not support membership testing.
7.A developer mistakenly believes `x and y` always returns a boolean. What does it actually return?
- AAlways the second operand
- BTrue or False only
- CThe first operand if it's falsy, otherwise the second
- DThe second operand if the first is falsy, otherwise True
8.What does the expression `'admin' not in user` check if `user = {'role': 'student'}`?
- AIf 'admin' is a substring of any value
- BIf 'admin' is a substring of any key
- CIf 'admin' is a key in the dictionary
- DIf 'admin' is a value in the dictionary