print(int和str)这是如何工作的?

时间:2018-02-27 16:21:00

标签: python python-3.x

我正在探索python的逻辑及其工作方式。 我想知道这段代码是如何工作的以及它实际上意味着什么使它能够提供这些结果..

代码:

print(str and int)
print(int and str)
print(str or int)
print(int or str)

结果:

<class 'int'>
<class 'str'>
<class 'str'>
<class 'int'>

4 个答案:

答案 0 :(得分:2)

来自python doc

 - x or y    -->  if x is false, then y, else x
 - x and y   -->  if x is false, then x, else y
 - not x     -->  if x is false, then True, else False

这意味着它返回的项目本身不仅仅是True或False

Here它提到: -

  

请注意,andor都不会限制它们返回的值和类型   到FalseTrue,而是返回最后一个评估的参数。

这就是str or int返回strstr and int返回int

的原因

答案 1 :(得分:1)

Python使用以下方法:

  1. 对于“and”运算符:

    • 如果左操作数为true,则检查并返回右操作数。
    • 如果左操作数为false,则返回。
  2. 对于“或”运营商:

    • 如果左操作数为true,则返回。
    • 如果左操作数为false,则返回右操作数。
  3. 在您的情况下,strint是类,因此评估为true,这完全解释了您观察到的内容。

答案 2 :(得分:0)

and为您提供检查的最后一个条件的最后一个对象,以检查它是true还是false,而or停在第一个过去了。因为strint都是true,因为它们是定义的对象,所以你得到它们

要证明你可以这样做:

print(str and int and bool) #<class bool>

你正在证明or

答案 3 :(得分:0)

i)Python有&#34; Truthy&#34;和Falsey值,意味着在逻辑运算的上下文中对象被评估为True或False。例如,以下代码打印出&#34; Yay!&#34;

if str:
    print("Yay!")

如果您将str替换为int

,则相同

ii)and一旦遇到虚假断言就终止; or遇到一个真正的断言。因此and返回了最后一个表达式,or返回了您案例中的第一个表达式,因为两个表达式都独立地计算为True。

相关问题