Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a python function passing an information to refer a case

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading