Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 试着/除了不抓住一个;大于;错误_Python_Django_Try Except - Fatal编程技术网

Python 试着/除了不抓住一个;大于;错误

Python 试着/除了不抓住一个;大于;错误,python,django,try-except,Python,Django,Try Except,以下代码不起作用: try: get_current_player(request).cash >= bid # does the player have enough cash for this bid ? except ValueError: messages.error(request, "You don't have the necessary funds to place a bid of <span class='cash'>%d</span&

以下代码不起作用:

try:
    get_current_player(request).cash >= bid # does the player have enough cash for this bid ?
except ValueError:
    messages.error(request, "You don't have the necessary funds to place a bid of <span class='cash'>%d</span> !" % (bid))
messages.success(request, "You placed a bid of %d !" % (bid))
试试看:
获取当前玩家(请求)。现金>=出价#玩家是否有足够的现金进行此出价?
除值错误外:
messages.error(请求“您没有必要的资金出价%d!”%(出价))
messages.success(请求“您出价%d!”%(出价))
当出价高于当前玩家的现金时,将打印成功消息而不是错误消息

但是,以下代码起作用,表明值是正确的:

if get_current_player(request).cash >= bid : # does the player have enough cash for this bid ?
    messages.success(request, "You placed a bid of %d !" % (bid))
else :
    messages.error(request, "You don't have the necessary funds to place a bid of <span class='cash'>%d</span> !" % (bid))
如果获得当前玩家(请求).cash>=出价:#玩家是否有足够的现金进行此出价?
messages.success(请求“您出价%d!”%(出价))
其他:
messages.error(请求“您没有必要的资金出价%d!”%(出价))

我使用try/except错误吗?

是的,您使用try/except错误。比较不会抛出任何异常,因为如果结果为假,则不例外。您的第二个代码是处理此类问题的正确方法。

您不应该使用
尝试
/
,除非您希望比较
获取当前玩家(请求)。cash>=bid
始终有效且不会产生错误。在第二个代码块中使用
if
/
else

在您的第一个代码块中,
获取当前玩家(请求)。cash>=bid
将被尝试并评估为
True
/
False
。只要此比较不产生
ValueError
(并且没有明显的原因),则不会执行
except

仅因为比较评估为
False
,所以
except
块不会运行

编辑:如果您认为评估
获取当前玩家(请求).cash>=bid
可能会引发异常,您可以将
If
/
else
块放入
try
块中:

try:
    if get_current_player(request).cash >= bid:
        messages.success(request, "You placed a bid of %d !" % (bid))
    else:
        messages.error(request, "You don't have the necessary funds to place a bid of <span class='cash'>%d</span> !" % (bid))

except ValueError:
    # handle the ValueError
试试看:
如果获得当前玩家(请求)。现金>=出价:
messages.success(请求“您出价%d!”%(出价))
其他:
messages.error(请求“您没有必要的资金出价%d!”%(出价))
除值错误外:
#处理ValueError
您可能希望考虑比较可能触发的任何其他错误(例如,
AttributeError
)。

为什么会这样

get_current_player(request).cash >= bid

应该返回错误吗?这是错的吗?不。这就是为什么你在这个问题上没有错误。

我明白了,谢谢。通常,现金应该足够了。这是一个罕见的事件,因为它不是。因此,在我看来,try/except是最好的方式,因为当我只想检查玩家是否有足够的现金时,它可以避免嵌套。有没有一种方法可以使用try/except来达到这个目的,或者这样做不是一种好的做法?@Brachamul您当然可以同时使用这两种方法-我已经相应地编辑了我的答案。