簡體   English   中英

檢查python中函數參數的范圍

[英]Checking range of function argument in python

如何處理數值上有效但物理上超出范圍的函數?

原因是,如果離開物理正確的范圍,我希望我的程序告訴我並停止。

我想過使用 ValueError 異常來處理這個錯誤。

例子:

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

對於這種參數限制,Python 有assert語句。

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

我不確定你所說的physically是什么意思。

一般來說,如果超出范圍的錯誤是由外部數據引起的,則應該引發異常; 如果錯誤來自您自己的數據,您可以使用assert來中止當前執行。

您可以簡單地將返回值限制為 T 如果它符合您的條件,否則return None ,如下所示:

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

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

編輯:解決方案有例外:

>>> 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

為了更清晰,您甚至可以輸出自己的消息:

>>> 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

您應該引發一個名為 ValueError 的異常。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM