Introduction :
The function ‘takeIntInput‘ serves as a tool for validating and processing integer input within Python. Its purpose is to examine whether the input provided is of type ‘ int’. If the input conforms to this requirement, the function returns a message confirming the data type and displaying the integer value. Conversely, if the input fails to meet the specified criteria, the function prompts the user to supply an integer data type instead.
This function proves particularly useful when ensuring that user input aligns with the expected data type before proceeding with subsequent operations, thereby enhancing program robustness and reliability.
content:
Here is a function called takeIntInput that validates and processes integer inputs in Python. This function will check if the input provided is of the int type. If it is, the function will return a message confirming the data type and displaying the integer value. Otherwise, it will prompt the user to provide an integer data type.
Code:
def sumOfNumbers(array): if isinstance(array, list) or isinstance(array, tuple): res = 0 for i in array: if isinstance(i, (int, float)): res += i return res if res else "Provide valid data" else: return "Provide either list or tuple with integers" tuple_array = (1, 2, 3, 5) print(sumOfNumbers([1, 5, 3])) print(sumOfNumbers(tuple_array)) print(sumOfNumbers(["s"])) print(sumOfNumbers("string"))
Explanation:
Function Definition: def takeIntInput(inputInt):
The function takes one argument inputInt.
Type Checking: if isinstance(inputInt, int):
The function checks if inputInt is an instance of int.
Return Statements:
If the input is an integer, the function returns a message confirming the data type and the value.
If the input is not an integer, the function returns a message asking for an integer input.
Example Usage:
print(takeIntInput(123)) returns “Input is of int data type which is 123” because 123 is an integer.
print(takeIntInput(“str”)) returns “Please provide int data type as input” because “str” is not an integer.
Output:
Input is off int data type which is 123 Please provide int data type as input