Python逻辑操作的三大重要环节

开发 后端
Python逻辑操作需要我们主要的地方有很多,其中有三个最重要的环节,下面我们就看看如何才能更好的避免这三个环节出错误。

Python逻辑操作的过程中有三个重要的环节。每一个都需要我们十分注意,下面我们就看看如何才能更好的运用Python逻辑操作中三个环节来完善我们的应用。希望大家在今后的学习中有所收获。举例:

  1. #coding:utf-8  
  2. test1 = 12 
  3. test2 = 0 
  4. print (test1 > test2) and (test1 > 14) #result = False 
  5. print (test1 < test2) or (test1 > -1) #result = True 
  6. print (not test1) #result = False 
  7. print (not test2) #result = True 

 

 

 

严格的说,逻辑操作符的操作数应该为布尔表达式。但Python对此处理的比较灵活。即使操作数是数字,解释器也把他们当成“表达式”。非0的数字的布尔值为1,0的布尔值为0.

举例:

  1. #coding:utf-8  
  2. test1 = 12 
  3. test2 = 0 
  4. print (test1 and test2) #result = 0 
  5. print (test1 or test2) #result = 12 
  6. print (not test1) #result = Flase 
  7. print (not test2) #reslut = True 

在Python中,空字符串为假,非空字符串为真。非零的数为真。
数字和字符串之间、字符串之间的逻辑操作规律是:
对于and操作符:只要左边的表达式为真,整个表达式返回的值是右边表达式的值,否则,返回左边表达式的值。对于or操作符:只要两边的表达式为真,整个表达式的结果是左边表达式的值。如果是一真一假,返回真值表达式的值,如果两个都是假,比如空值和0,返回的是右边的值。(空值或0)

举例:

  1. #coding:utf-8   
  2. test1 = 12   
  3. test2 = 0   
  4. test3 = ''   
  5. test4 = "First"   
  6. print test1 and test3 #result = ''   
  7. print test3 and test1 #result = ''   
  8. print test1 and test4 #result = "First"   
  9. print test4 and test1 #result = 12 
  10. print test1 or test2 #result = 12 
  11. print test1 or test3 #result = 12 
  12. print test3 or test4 #result = "First" 
  13. print test2 or test4 #result = "First" 
  14. print test1 or test4 #result = 12 
  15. print test4 or test1 #result = "First" 
  16. print test2 or test3 #result = '' 
  17. print test3 or test2 #result = 0 

以上就是对Python逻辑操作的相关介绍。希望大家有所收获。

【编辑推荐】

  1. Python源码的三大应用技术
  2. Python循环如何解决无限循环
  3. Python编程不同于其他编程语言的优点
  4. Python语言开发中的六大应用方式
  5. Python连接数据库如何解决中文乱码
责任编辑:张浩 来源: 博客园
相关推荐

2010-03-11 19:45:09

Python逻辑

2021-03-08 15:24:18

云计算私有云云安全

2023-12-31 13:05:19

pytorch深度学习框架

2009-06-19 11:38:15

JavaFX 1.2

2020-09-06 08:26:59

Python 3开发代码

2012-11-21 10:45:06

2015-11-04 12:02:46

桌面虚拟化

2019-02-26 09:00:00

人工智能AI保险

2010-03-10 13:42:44

Python脚本

2010-03-11 15:01:52

Python源码

2018-06-14 14:07:57

Pythonweb框架

2020-05-28 16:38:50

新基建智慧城市重构

2010-04-16 09:27:36

2010-09-30 16:06:21

J2ME平台

2012-08-24 11:00:31

2017-10-18 23:15:52

物联网产业链网络

2009-10-26 17:07:17

VB.NET UNDO

2013-09-25 17:06:34

Windows Azu微软CloudOS

2020-02-07 09:59:29

Python异常处理语言

2013-12-02 14:29:27

jQuery元素属性
点赞
收藏

51CTO技术栈公众号