Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.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_If Statement - Fatal编程技术网

Python &引用;如果是;,及;以英语发言;链与素的对比;如果;链条

Python &引用;如果是;,及;以英语发言;链与素的对比;如果;链条,python,if-statement,Python,If Statement,我想知道,既然可以这样做,为什么还需要使用elif if True: ... if False: ... ... 当您希望确保只拾取一个分支时,可以使用elif: foo = 'bar' spam = 'eggs' if foo == 'bar': # do this elif spam == 'eggs': # won't do this. 将此与: foo = 'bar' spam = 'eggs' if foo == 'bar': # do

我想知道,既然可以这样做,为什么还需要使用
elif

if True:
    ...
if False:
    ...
...

当您希望确保只拾取一个分支时,可以使用
elif

foo = 'bar'
spam = 'eggs'

if foo == 'bar':
    # do this
elif spam == 'eggs':
    # won't do this.
将此与:

foo = 'bar'
spam = 'eggs'

if foo == 'bar':
    # do this
if spam == 'eggs':
    # *and* do this.
仅使用
if
语句,选项不是独占的

if
分支更改程序状态,使得
elif
测试也可能为真时,这也适用:

foo = 'bar'

if foo == 'bar':
    # do this
    foo = 'spam'
elif foo == 'spam':
    # this is skipped, even if foo == 'spam' is now true
    foo = 'ham'
此处
foo
将设置为
“垃圾邮件”

foo = 'bar'

if foo == 'bar':
    # do this
    foo = 'spam'
if foo == 'spam':
    # this is executed when foo == 'bar' as well, as 
    # the previous if statement changed it to 'spam'.
    foo = 'ham'
现在
foo
设置为
'spam'
,然后设置为
'ham'

foo = 'bar'

if foo == 'bar':
    # do this
    foo = 'spam'
if foo == 'spam':
    # this is executed when foo == 'bar' as well, as 
    # the previous if statement changed it to 'spam'.
    foo = 'ham'

从技术上讲,
elif
是(复合)
if
语句的一部分;Python在一系列测试为true的
if
/
elif
分支中选择第一个测试,如果没有一个分支为true,则选择
else
分支(如果存在)。使用一个单独的
if
语句启动一个新的选择,独立于前面的
if
复合语句。

itertools.count
是一个生成器,每次调用它时都会给你一个新值,因此它对于说明这类事情很有用

from itertools import count
c = count()
print(next(c)) # 0
print(next(c)) # 1
print(next(c)) # 2
if True:
  print(next(c)) # 3
if True:
  print(next(c)) # 4
elif True:
  print(next(c)) # … not called
print(next(c)) # 5
最后一个值必须是6,才能使
elif
if
相同。但发电机也可能“用完”,这意味着您需要能够避免对其进行两次检查

if 6 == next(c):
  print('got 6') # Printed!
if (7 == next(c)) and not (6 == next(c)):
  print('got 7') # Also printed!
不一样

if 9 == next(c):
  print('got 9') # printed
elif 10 == next(c):
  print('got 10') # not printed!

@Hyperboreus这完全是错误的,你最好删除你的评论。@Hyperboreus是认真的吗?@Hyperboreus:恐怕这是完全错误的。如果
if
分支中的代码禁用了
A
,该怎么办?@Hyperboreus:我添加了一个例子,说明为什么
elif
不仅仅是语法上的糖分。@Hyperboreus:现在你只是在假设;当然,我也可以通过
while
循环来实现
for