marou
marou

Reputation: 115

Checking range of function argument in python

What to do with functions which are numerically valid, but physically out of range?

The reason, I would like my programm to tell me and stop, if the physically correct range is left.

I thought about using the ValueError exception for this error handling.

Example:

def return_approximation(T):
  #return T only if it is inbetween 0 < T < 100
  return T

Upvotes: 1

Views: 2865

Answers (4)

VoteCoffee
VoteCoffee

Reputation: 5107

You should raise an exception called ValueError.

if 0 < T < 100:
    raise ValueError('T must be in the exclusive range (0,100)')

Upvotes: 2

Iron Fist
Iron Fist

Reputation: 10951

You can simply, restrict the returned value to T if it matches your conditions else return None, like so:

>>> def f(T):
        return T if 0 < T < 100 else None

>>> f(100)
>>> f(99)
99
>>> f(0)
>>> f(1)
1

EDIT: solution with exceptions:

>>> def f(T):
        if 0 < T < 100:
            return T
        else:
            raise ValueError


>>> f(100)
Traceback (most recent call last):
  File "<pyshell#475>", line 1, in <module>
    f(100)
  File "<pyshell#474>", line 5, in f
    raise ValueError
ValueError
>>> f(99)
99
>>> f(0)
Traceback (most recent call last):
  File "<pyshell#477>", line 1, in <module>
    f(0)
  File "<pyshell#474>", line 5, in f
    raise ValueError
ValueError
>>> f(1)
1

You can even output your own message for more clarity:

>>> def f(T):
        if 0 < T < 100:
            return T
        else:
            raise Exception('T is out of Range')

>>> f(100)
Traceback (most recent call last):
  File "<pyshell#484>", line 1, in <module>
    f(100)
  File "<pyshell#483>", line 5, in f
    raise Exception('T is out of Range')
Exception: T is out of Range

Upvotes: 0

hpwsue
hpwsue

Reputation: 21

I'm not sure about what you mean by physically.

Generally speaking, if the out-of-range error is caused by external data, you're supposed to raise an exception; if the error comes from your own data, you may use assert to abort the current execution.

Upvotes: 0

mkiever
mkiever

Reputation: 891

Python has the assert-statement for this kind of argument restrictions.

def return_approximation(T):
    assert 0 < T < 100, "Argument 'T' out of range"
    return T

Upvotes: 8

Related Questions