Bird
0
0

You want to write a function that returns True if the input is an integer or a float, and False otherwise. Which code correctly uses type() to do this?

hard📝 Application Q15 of 15
Python - Variables and Dynamic Typing
You want to write a function that returns True if the input is an integer or a float, and False otherwise. Which code correctly uses type() to do this?
Adef check_num(x): return type(x) == int and float
Bdef check_num(x): return type(x) == int or float
Cdef check_num(x): return type(x) == 'int' or 'float'
Ddef check_num(x): return type(x) in [int, float]
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    The function should return True if x is either int or float.
  2. Step 2: Analyze each option's correctness

    def check_num(x): return type(x) == int or float uses or float incorrectly, always returning truthy. def check_num(x): return type(x) in [int, float] uses in to check membership in a list of types, which is concise and correct. def check_num(x): return type(x) == 'int' or 'float' compares type to strings, which is wrong. def check_num(x): return type(x) == int and float uses and incorrectly, only detecting ints.
  3. Final Answer:

    def check_num(x): return type(x) in [int, float] -> Option D
  4. Quick Check:

    Use in to check multiple types [OK]
Quick Trick: Use 'type(x) in [int, float]' for multiple types [OK]
Common Mistakes:
MISTAKES
  • Comparing type to string names
  • Using 'and' instead of 'or' or 'in'
  • Using incomplete logic like '== int or float'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes