Python中的and/or

在Python中,可以通过and,or和not进行逻辑运算,下面就来看看and和or的简单介绍。

逻辑与-and

对于包含and运算的表达式,Python解释器将从左到右扫描,返回第一个为假的表达式值,无假值则返回最后一个表达式值

下面看一个使用and的例子:

# if all the expressions are true, return the last expression
print {"name": "Will"} and "hello" and 1

# return the first false expression
print {"name": "Will"} and "" and 1
print {"name": "Will"} and [] and 1
print {} and [] and None
print {"name": "Will"} and [1] and None

代码的输出为下:

逻辑或-or

对于包含or运算的表达式,Python解释器将从左到右扫描,返回第一个为真的表达式值,无真值则返回最后一个表达式值

看下面的例子:

# if all the expressions are false, return the last expression
print {} or [] or None

# return the first true expression
print {"name": "Will"} or "hello" or 1
print {} or [1] or 1
print {} or [] or "hello"

代码的输出如下:

三目运算符

很多语言中都支持三目运算符"bool?a:b",虽然在Python中不支持三目运算符,但是可以通过and-or达到同样的效果。

expression_1 and expression_2 or expression_3

看代码:

a = "hello"
b = "will"

# bool?a:b
print True and a or b
print False and a or b

这个例子通过and-or模拟了三目运算符,当第一个表达式expression_1为True的时候,整个表达式的值就是expression_2表达式的值:

安全的and-or

其实上面使用and-or模拟三目运算符的方式并不安全,看下图:

如果expression_2本身的值就是False,那么无论expression_1的值是什么,"expression_1 and expression_2 or expression_3"的结果都会是expression_3。

可以通过简单的代码就行验证:

a = []
b = "will"

# bool?a:b
print True and a or b
print False and a or b

代码输出为:

那么为了避免这种问题,可以使用下面的方法,将expression_2和expression_3存放在list中:

(expression_1 and [expression_2] or [expression_3])[0]

例如:

a = []
b = "will"

# bool?a:b
print (True and [a] or [b])[0]
print (False and [a] or [b])[0]

代码的运行效果为下,即使expression_2为False,但是[expression_2]仍是非空列表:

总结

本文通过一些简单的例子,演示了Python中and和or的使用。

并通过and-or方式实现了三目运算符的效果。

时间: 2024-08-26 03:21:42

Python中的and/or的相关文章

走入计算机的第四十天(python中sockserver模块)

一.Python中的sockserver模块 1.该模块与sock模块不同之处是该模块自动帮我们分装好了一些功能,让我们在编程的时候直接调用这些功能就可以了,节省了编程步骤. 2.如图所示 注释:上图为服务端设置 该模块的操作方法比较死板,我们只要会熟悉的使用他就可以了.

python中if __name__ == '__main__':

Using a module's __name__ Example? 8.2.? Using a module's __name__ #!/usr/bin/python # Filename: using_name.py if __name__ == '__main__': print 'This program is being run by itself' else: print 'I am being imported from another module' Output $ pytho

关于Python中的yield

关于Python中的yield http://www.cnblogs.com/tqsummer/archive/2010/12/27/1917927.html http://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/ 一.迭代器(iterator) 在Python中,for循环可以用于Python中的任何类型,包括列表.元祖等等,实际上,for循环可用于任何“可迭代对象”,这其实就是迭代器 迭代器是一个实现了迭代器协议

python中的那些“神器”

"武林至尊,宝刀屠龙,号令天下,莫敢不从,倚天不出,谁与争锋",这是神器.不过今天要说的python中的"神器"就没有这么厉害了,这里要说的"神器"其实就是名称里面带了个"器"的,如下: 列表解析器 迭代器 生成器 装饰器 列表解析器 现在遇到了这样一个问题需要解决:"有一个数字的列表,要求对该列表中的奇数乘以2,返回处理完成后的列表(不改变原来列表的顺序,仅对列表中的奇数乘以2)",比较传统的方法可能会是

Python中字符串格式化如何实现?

Python开发中字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存. This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing '%' string formatting operator. 1.百分号方式 %[(na

python 中*args 和 **kwargs

简单的可以理解为python 中给函数传递的可变参数,args 是 列表的形式.kwargs 是 key,value的形式,也就是python 中的字典. *args 必须出现在**kwargs 的前边,否则会抛异常. 1 def test(*args, **kwargs): 2 print args 3 print kwargs 1 if __name__ == '__main__': 2 print '---test 1---' 3 test(1, 2, 3) 4 print '---tes

python中super出现的TypeError: must be type, not classobj 原因及解决

执行一下代码,出现错误,TypeError: must be type, not classobj class A():    def __init__(self):        print("Enter A")        print("Leave A") class B(A):    def __init__(self):        print("Enter B")        super(B, self).__init__()  

python中的切片问题

对于在一个字符串中选取几个字符,不同的语言有不同的解决方案,python 中就有了切片的方法.    在list中,如下:     s=list(range(1,101))    如果想要选取偶数个数字(或者选取偶数),可以用循环的方法:但是方法臃肿,比较"笨"    但是python中给出的切片方法是更加的优雅的,如下:    L=list(range(1,101))    print(L[0])    print(L[0:10])#输出结果是[1, 2, 3, 4, 5, 6, 7

Python学习-16.Python中的错误处理

虽然叫错误,但跟 C# 中的异常是一回事.只不过 Python 中叫错误(Error)而 C# 中叫异常(Exception). 先手工产生一个异常: 1 file = open('','r') 上面一句由于路径是空路径,因此文件肯定是不存在的,执行这一句会引发 FileNotFoundError 这个错误. 既然是错误的,程序也停止了,这是我们不希望的,因此得想办法处理一下. 在 Python 中,异常处理使用 try.except.finally 这三个关键字. 修改代码如下: 1 path

python中各种基础类型的转换,二进制,八进制,十进制,十六进制

python中所有类型都是作为对象的形式来存在的. 在python中没有char型,只有字符串类型,这样我们可能将char型转换为整型时极不方便,但是python已经提供了这些转换的内置函数. python 中除了整型,其他进制的只能用字符串来表示 1 int() 可以将 二进制,八进制,十六进制转换成十进制整型 >>> int('1111', 2) 15 >>> int('f', 16) 15 >>> int('17', 8) 15 2 chr()