Python入门-逻辑运算符、if条件表达式


一、逻辑运算符号

主要涉及到==、and、or、not四个逻辑运算符号

1、逻辑相等(==)

仅当p或q包含的值相同的时候,即都为True或都为False的时候,表达式p==q的结果才为True.表达式p!=q检验p和q是否不同,仅在p和q在不同的时候,才返回True.

>>> False==True
False
>>> True==False
False
>>> True==True
True
>>> False!=False
False
>>> True!=False
True
>>> True!=True
False
2、逻辑与(and)

当p和q同时都True时候,才为True,其他情况都为False

>>> False and False
False
>>> False and True
False
>>> True and True
True
>>> True and False
False
3、逻辑或(or)

仅当p和q至少有一个为True的时候,p or q 才为True.

>>> False or False
False
>>> False or True
True
>>> True or False
True
>>> True or True
True
4、逻辑非(not)

在P为False的时,表达式 not p为True;在p为True时,not p为False

>>> not True
False
>>> not False
True

二、条件语句

1、if语句

if条件判断语句,后面需要加入一个冒号(:)

例如:

#if.py
password=input('what is your name?')
if password=='intely':
   print('please logging on ...')
else:
   print('Incorrect password.')
print('All done.')
               
结果是:

>>> 
what is your name?intely
please logging on ...
All done.
程序理解是:如果输入的password为intely,则进行登陆;否则就退出。然后最后一条信息就是输出All done.

2、if/elif语句

if/elif语句则是if语句的推广版本,包含多个条件,如某游乐园提供儿童优惠价:不超过3岁则免费;4~15岁儿童打折;15岁以上的与大人同价。程序如下:

#elif
age=int(input('How old are you?'))
if age<=3:
    print('free')
elif age>3 and age<15:
    print('child fare')
else:
    print('adult fare')
结果如下:

>>> 
How old are you?4
child fare












  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值