I would like to create a function where we can specify an information as a string input. The result will be change by the information and an error might be raised if the information is not correct
i mean something like this small example :
def f(a,b,method='repartition uniforme'):
if method=='repartition uniforme':
return a+b
if method=='repartition fin de ligne':
return a*b
else:
raise NameError('méthode de répartition des charge non valide')
What is the best and proper way to create this kind of function ?
>Solution :
Your code is fine with one exception – NameError is usually reserved for namespace errors, while what you want is ValueError which is commonly used for argument values of correct type but outside of expected range.
Since Python 3.10 you can use match statements instead of chained ‘if’s to make it more readable. Your code would look like that using that syntax:
def f(a,b,method='repartition uniforme'):
match method:
case 'repartition uniforme':
return a+b
case 'repartition fin de ligne':
return a*b
case _:
raise ValueError('méthode de répartition des charge non valide')