掌握Python的X篇_9_关系运算符与逻辑运算符

文章介绍了Python中的True和False关键字,以及关系运算符如>、<、==、!=、is、isnot的用法。同时,讨论了逻辑运算符not、and、or如何结合关系表达式进行布尔逻辑判断。文中通过示例代码展示了这些运算符的工作原理,并给出了使用警告的情况。

1. True与False关键字

Python中有True和False关键字,对应了生活中的“真”、“假”

2. 关系运算符

python中有以下的关系运算符,用于比较两个操作数(变量/常量)的关系:

>
<
==
!=
is
is not
in 
not in

其中的in和not in操作符需要有容器的知识,暂时不讨论
使用关系运算符,可以得到True或者False的结果。

In [1]: 5 > 3
Out[1]: True

In [2]: 5 < 3
Out[2]: False

In [3]: a=4

In [4]: 3==a
Out[4]: False

In [5]: 2!=3
Out[5]: True

In [6]: 5 is 5
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<ipython-input-6-20faadc7ecbf>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
  5 is 5
Out[6]: True

In [7]: 5 is 3
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<ipython-input-7-772e5d83037e>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
  5 is 3
Out[7]: False

In [8]: 5 is not 3
<>:1: SyntaxWarning: "is not" with a literal. Did you mean "!="?
<ipython-input-8-2e3baa52640e>:1: SyntaxWarning: "is not" with a literal. Did you mean "!="?
  5 is not 3
Out[8]: True

isis not,其实是与==!=是一致的

3. 逻辑运算符

逻辑运算符可以用于连接关系表达式

  • not:逻辑取反,原有的True改为False;原有的False变为True
In [10]: not True
Out[10]: False
In [11]: not (5>3)
Out[11]: False
  • and:二元运算符
(表达式) and (表达式)

只有当2个表达式都为True时,才可以得到True的结果;其他情况均为False

In [12]: money = 100

In [13]: beauty = 100

In [14]: money > 60 and beauty > 60
Out[14]: True
  • or:二元运算符
(表达式) or (表达式)

只有当2个表达式都为False时,才会得到False的结果;其他情况均为True

In [15]: money =50

In [16]: money > 60 or beauty > 60
Out[16]: True

4.学习视频地址:关系运算符与逻辑运算符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十月旧城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值