Python Forum
Parameters type in a function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Parameters type in a function
#1
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)
Reply
#2
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.
Reply
#3
+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).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  determine parameter type in definition function akbarza 1 550 Aug-24-2023, 01:46 PM
Last Post: deanhystad
Question How to compare two parameters in a function that has *args? Milan 4 1,183 Mar-26-2023, 07:43 PM
Last Post: Milan
  declaring object parameters with type JonWayn 2 856 Dec-13-2022, 07:46 PM
Last Post: JonWayn
  i want to use type= as a function/method keyword argument Skaperen 9 1,776 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  function accepts infinite parameters and returns a graph with those values edencthompson 0 812 Jun-10-2022, 03:42 PM
Last Post: edencthompson
  match type with value in csv parsing function vinci 2 1,268 Jan-21-2022, 12:19 PM
Last Post: Larz60+
  How can I write a function with three parameters? MehmetAliKarabulut 1 2,377 Mar-04-2021, 10:47 PM
Last Post: Larz60+
  Parameters aren't seen inside function Sancho_Pansa 8 2,815 Oct-27-2020, 07:52 AM
Last Post: Sancho_Pansa
  RuntimeError: Optimal parameters not found: Number of calls to function has reached m bntayfur 0 6,073 Aug-05-2020, 04:41 PM
Last Post: bntayfur
  Function parameters and values as string infobound 1 1,728 Jul-24-2020, 04:28 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020