Python Forum

Full Version: Parameters type in a function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Quick question:
How do you edit the code below so that the paramater in the sum function must be a number? So x MUST be a number.
global_var=5

def sum(x=5):
    ret_val = global_var * x
    print(ret_val)
You can't. That's part of the whole point of python.

You can use type hinting, to suggest that it's a number:
>>> def sum(x : float = 5):
...   print(x)
...
>>> sum()
5
>>> sum(83.2)
83.2
>>> sum("carrot")
carrot
But that's still just a suggestion. You could check the type yourself, and throw an error if it's that important (or return a different value, depending on what makes sense):
>>> def sum(x=5):
...   if not isinstance(x, int) and not isinstance(x, float):
...     raise TypeError(f"Number expected, {type(x)} found instead.")
...   return x ** 2
...
>>> sum()
25
>>> sum(7.4)
54.760000000000005
>>> sum("carrot")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in sum
TypeError: Number expected, <class 'str'> found instead.
+1 to everything nilamo said, but also that you might want to use an ABC rather than explicitly specifying int and float (also instead of two isinstance calls, you can provide a tuple of acceptable types).