227k views
5 votes
including how it can be stored and what types of operations we can perform. For example, we can write a program that squares numbers, but it wouldn’t be able to square a word.

User BattleBit
by
7.7k points

1 Answer

4 votes

Answer:

The solution code is written in Python:

  1. def square(num):
  2. if type(num).__name__ == 'int':
  3. sq_num = num * num
  4. return sq_num
  5. else:
  6. return "Invalid input"
  7. print(square(5))
  8. print(square("Test"))

Step-by-step explanation:

To ensure only certain type of operation can be applied on a input value, we can check the data type of the input value. For example, we define a function and name it as square which take one input number, num (Line 1).

Before the num can be squared, it goes through a validation mechanism in by setting an if condition (Line 2) to check if the data type of the input number is an integer, int. If so, the num will only be squared otherwise it return an error message (Line 6).

We can test our function by passing value of 5 and "Test" string. We will get program output:

25

Invalid input

User Raksheetbhat
by
8.0k points