链式条件的Python语法

Jas*_*JH. 5 python conditional-operator

我是Python的初学者,目前正在通过"如何像计算机科学家一样思考"这本书进行自学.从关于链式条件的书中练习,语法教导是:

 def function(x,y)
   if ..:
      print ".."
   elif..:
      print ".."
   else:
      print".."
Run Code Online (Sandbox Code Playgroud)

但是,当我试图找出它是否合法时,它起作用了:

 def function (x,y)
   if ..:
     print ".."
   if ..:
     print ".."
Run Code Online (Sandbox Code Playgroud)

后者是正确的语法吗?或者它甚至不被视为链式条件?我想知道即使这在Python中是合法的,它是编写代码的"好方法"吗?

真诚地感谢所有的帮助.

Mic*_*ski 13

虽然你的第二个例子是工作,这是一样的东西作为第一个例子.在第二种if情况下,将评估每个条件,无论前一个条件是否为真并执行.在链接的if/elif示例中,整个事物被视为一个单元,只执行第一个匹配的条件.

例如:

# An if/elif chain
a = 2
b = 3

if a == 2:
  print "a is 2"
elif b == 3:
  print "b is 3"
else:
  print "whatever"

# prints only
"a is 2"
# even though the b condition is also true.
Run Code Online (Sandbox Code Playgroud)

然而

# Sequential if statements, not chained
a = 2
b = 3

if a == 2:
  print "a is 2"

if b == 3:
  print "b is 3"

# prints both
"a is 2"
"b is 3"
Run Code Online (Sandbox Code Playgroud)