Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.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_Python 3.x - Fatal编程技术网

Python如果检查错误

Python如果检查错误,python,python-3.x,Python,Python 3.x,当我使用代码时: def Jack(): global PHand if 11 or 24 or 37 or 50 in PHand: PHand.remove(11 or 24 or 37 or 50) PHand.append("Jack") 我得到一个错误列表。删除(x)x不在PHand中,我的问题是,if检查是否应该防止此错误?您基本上是在检查11是否为真。它不是零,所以您的if总是执行。你想要的是: if 11 in PHand or

当我使用代码时:

def Jack():
    global PHand
    if 11 or 24 or 37 or 50 in PHand:
        PHand.remove(11 or 24 or 37 or 50)
        PHand.append("Jack")

我得到一个错误列表。删除(x)x不在PHand中,我的问题是,if检查是否应该防止此错误?

您基本上是在检查
11
是否为真。它不是零,所以您的
if
总是执行。你想要的是:

if 11 in PHand or 24 in PHand or 37 in PHand or 50 in Phand:
当然,出于同样的原因,您的
PHand.remove
总是尝试删除
11
。您无法告诉
remove
删除其中任何一个(不确定您从何处获得的想法是否可行,我从未见过任何文档中有此想法),因此您应该将其结构化为:

if 11 in PHand:
   PHand.remove(11)
   PHand.append("Jack")
if 24 in PHand:
   PHand.remove(24)
   PHand.append("Jack")
。。。等等


当然,您最好将其重构为循环甚至函数,而不是重复所有代码。

您需要迭代每个元素:

for i in (11, 24, 37, 50):   # assign i to 11, then 24, then 37, then 50
    if i in PHand:           # check each one in PHand
        PHand.remove(i)      # and remove that one
        PHand.append("Jack") # your code
        break                # end the loop. remove this to check all
否则,PHand中的
11或24或37或50将输出
11
。试试看

>>> 11 or 24 or 37 or 50 in PHand
11
为什么??按照
的工作方式,它检查第一面是否真实。如果是的话,它就不需要评估其余的,因为结果不会改变。如果这不是真的,它会继续下一个论点,依此类推

那么PHand中的
呢?它实际上首先被计算到最后一个数字,如下所示:

11 or 24 or 37 or (50 in PHand)
但同样,11条线路将所有
短路


长话短说:


或始终返回一个值,而不是一次将所有值重复应用于函数,或按语法所示方式应用于函数。

只是使用筛选器解决此问题的另一种方法:

  def Jack():
      T = [11,24,37,50]
      found = filter(lambda x:x in T, PHand)
      if found:
          [PHand.remove(x) for x in found]
          PHand.append('Jack')

  PHand = range(10,55)
  Jack()

你到底想干什么?这些数字有什么特别之处?