Do one of the input values have to share the same data type as the return value?


#1

Question

In a Python function, do at least one of the input values have to share the same data type as the return value?

Answer

No, none of the parameter values must match the return value’s type. Parameters and return values of a function have no real intrinsic connection. The connection, if any, is made by us when writing the code, and deciding what the code itself does inside the function, which can have the return type be the same as the input value type. However, neither will be constrained to the other’s data type, unless we implemented it that way.

Example

# The input values are numbers,
# while the return value is a string.
def abc_repeater(a_repeats=0, b_repeats=0, c_repeats=0):
  return "a" * a_repeats + "b" * b_repeats + "c" * c_repeats

# This will output “aaaaabbbbbccccc”
print(abcRepeater(5, 5, 5)) 

# The input value must be a number for this function.
# This is because of how the code was written, 
# rather than a strict rule.
def add_ten(num):
  return num + 10