Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Type check

Write a function named only_ints that takes two parameters. Your function should return True if both parameters are integers, and False otherwise.

For example, calling only_ints(1, 2) should return True, while calling only_ints("a", 1) should return False.

 

 

==== SOLUTION ====

You can implement the `only_ints` function in Python by using the `isinstance()` function to check if both parameters are of type `int`. Here’s how you can do it:

“`python
def only_ints(x, y):
      return isinstance(x, int) and isinstance(y, int)

# Test the function
print(only_ints(1, 2)) # Output: True
print(only_ints(“a”, 1)) # Output: False
“`

Explanation:

1. `def only_ints(x, y):`: This line defines a function named `only_ints` that takes two parameters, `x` and `y`.

2. `isinstance(x, int)`: This part checks if the variable `x` is of type `int`. It returns `True` if `x` is an integer, and `False` otherwise.

3. `isinstance(y, int)`: Similarly, this part checks if the variable `y` is of type `int`.

4. `return isinstance(x, int) and isinstance(y, int)`: This line returns `True` only if both `x` and `y` are integers. Otherwise, it returns `False`.

So, when you call `only_ints(1, 2)`, it returns `True` because both parameters are integers. Conversely, when you call `only_ints(“a”, 1)`, it returns `False` because one of the parameters is not an integer.

Join the conversation