Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.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 else块从不执行_Python_If Statement - Fatal编程技术网

Python else块从不执行

Python else块从不执行,python,if-statement,Python,If Statement,我试图将用户输入与列表的每个元素进行比较,其中NL是列表,但由于某些原因,它从未进入else循环 NL = range(1, sc.NLayer + 1) if (x for x in NL if x < sc.NLayer): print 'true' else: print 'false' NL=范围(1,sc.NLayer+1) 如果(如果x小于sc.NLayer,则NL中的x为x): 打印“真” 其他: 打印“假” sc.NLayer是用户输入 假设sc.N

我试图将用户输入与列表的每个元素进行比较,其中NL是列表,但由于某些原因,它从未进入else循环

NL = range(1, sc.NLayer + 1)

if (x for x in NL if x < sc.NLayer): 
    print 'true'
else:
    print 'false'
NL=范围(1,sc.NLayer+1)
如果(如果x小于sc.NLayer,则NL中的x为x):
打印“真”
其他:
打印“假”
sc.NLayer
是用户输入

假设sc.NLayer=5;它没有达到else条件。请帮帮我是的,不

if any(x for x in NL if x <sc.NLayer): 
  print 'true'
else:
  print 'false'

如果有(NL中的x代表x如果x您可能希望使用内置的
any
功能

any([True, False, 0, []])
=> True
因此,在您的代码中,它将是:

if any(x for x in NL if x < sc.NLayer):
    print 'true'
else:
    print 'false'
如果有(如果x
或者可能是for循环:

for x in NL:
    if x < sc.NLayer:
        print 'true'
    else:
        print 'false'
NL中x的
:
如果x
如果其他回答不清楚,您的问题就在这里:

if (x for x in NL if x < sc.NLayer):
这是您的空列表。现在使用
bool()
对其进行评估,并观察它是否为
False

>>> bool([x for x in mylist if x == 'a'])
False
好的,那么如果将其作为生成器表达式进行求值会怎么样:

>>> (x for x in mylist if x == 'a')
<generator object <genexpr> at 0xb7ebc644>
>>> bool((x for x in mylist if x == 'a'))
True

我希望这会有帮助!

我不明白这段代码要检查什么。你能用简单的英语解释一下吗?我可以告诉你为什么它会这样做,但Matti是对的:为了解决你的实际问题,我们需要了解你在尝试做什么,因为你的代码目前很无意义,最好你解释一下d您想要什么。我试图将用户输入与列表中的每个元素进行比较,其中NL是列表。当其中一个输入为
True
时,您的第一个代码示例显示
True
。需要注意的是,与
不同,
any()
all()
没有合并。
>>> (x for x in mylist if x == 'a')
<generator object <genexpr> at 0xb7ebc644>
>>> bool((x for x in mylist if x == 'a'))
True
>>> list((x for x in mylist if x == 'a'))
[]