1

我无法理解我在 Python 中看到的一些简写符号。请问有人可以解释这两个功能之间的区别吗?谢谢你。

def test1():
   first = "David"
   last = "Smith"
   if first and last:
      print last


def test2():
   first = "David"
   last = "Smith"
   print first and last
4

3 回答 3

5

第一个函数总是返回None(打印Smith),而第二个函数总是返回"Smith"*

快速题外话and

pythonand运算符返回它遇到的第一个“假”值。如果它没有遇到“假”值,则返回最后一个值(即“true-y”)这解释了原因:

"David" and "Smith"

总是返回"Smith"。由于两者都是非空字符串,它们都是“真-y”值。

"" and "Smith"

会返回"",因为它是一个虚假值。


* OP 发布的原始函数实际上是这样的:

def test2():
   first = "David"
   last = "Smith"
   return first and last
于 2013-04-11T15:17:21.787 回答
3

test1()函数和之间的区别在于,只要表达式的结果为真,就会显式打印 的值,并test2()打印test1()表达式的结果。打印的字符串是相同的,因为表达式的结果是 - 的值,但仅仅是因为计算结果为真。lastfirst and lasttest2()first and lastfirst and lastlastfirst

在 Python 中,如果表达式的左侧and计算结果为真,则表达式的结果是该表达式的右侧。由于布尔运算符的短路,如果and表达式的左侧计算为假,则返回表达式的左侧。

or在 Python 中也会短路,返回表达式最左边的值,它决定了整个表达式的真值。

所以,看看更多的测试功能:

def test3():
    first = ""
    last = "Smith"
    if first and last:
        print last

def test4():
    first = ""
    last = "Smith"
    print first and last

def test5():
    first = "David"
    last = "Smith"
    if first or last:
        print last

def test6():
    first = "David"
    last = "Smith"
    print first or last

def test7():
    first = "David"
    last = ""
    if first or last:
        print last

def test8():
    first = "David"
    last = ""
    print first or last

test3()不会打印任何东西。
test4()将打印""

test5()将打印"Smith"
test6()将打印"David"

test7()将打印""
test8()将打印"David"

于 2013-04-11T15:49:08.530 回答
0

你问,这两个片段之间有什么区别?

if first and last:
  print last

print first and last

在第一种情况下,代码要么打印 last 的值,要么不打印。

在第二种情况下,代码将打印 的值first and last。如果您习惯于 C,那么您可能会认为 的值a and b是布尔值 True 或 False。但你错了。

a and b评估a;如果a为真,则表达式的值为b。如果a是错误的,则表达式的值为a

"David" and "Smith" -> "Smith"
0 and "Smith" -> 0
1 and "Smith" -> "Smith" 
"David" and 0 -> 0
"David" and 1 -> 1

一般来说:

  • 第一个有时会打印一些东西,而其他时候不打印一些东西。
    • 第二个总是打印一些东西。
  • 第一个打印last,如果它打印任何东西
    • 根据 的真实性,第二个打印要么first要么。lastfirst

具体来说,如果firstis ever "",则第二个示例将打印"",而第一个示例根本不会打印任何内容。

于 2013-04-11T15:57:20.063 回答