Python快速入门(下)

环境安装

参见Python快速入门(上)

python基础

条件判断

描述

条件判断可描述为:

  • 如果满足条件condition_1,则执行语句statement_1,否则执行statement_other
  • 如果满足条件condition_1,则执行语句statement_1,如果不满足条件condition_1而满足条件condition_2,则执行语句statement_2,如果不满足条件condition_1condition_2而满足条件condition_3,则执行statement_3,···所有条件都不满足,则执行statement_other
范例

饮水的最适温度为52-70

if-else 结构
water_temperature_todrink = 55
if water_temperature_todrink > 70:
    print('it is so hot to drink')
else:
    print('ok,it is fine')
output:ok,it is fine
if-elif-else 结构
#结构中可以添加多层elif
water_temperature_todrink = 40
if water_temperature_todrink > 70:
    print('it is so hot to drink')
elif water_temperature_todrink >55:
    print('ok,it is best to drink')
else:
    print('maybe it is a little cold')
output:maybe it is a little cold

嵌套结构
water_temperature_todrink = -10
if water_temperature_todrink > 70:
    print('it is so hot to drink')
elif water_temperature_todrink >55:
    print('ok,it is best to drink')
else:
    if water_temperature_todrink <0:
        print('it is just an ice cube, I can not drink it')
    else:
        print('maybe it is a little cold')
        
output:it is just an ice cube, I can not drink it

断言

结构如下

assert condition,statement

表示如果conditionFalse,则输出statement。断言是程序开发中调试的一种手段。

范例

person = "侯亮平"
condition = ( person != "侯亮平")
assert condition,"京州不允许这么牛逼的人物存在"

output:
AssertionError: 京州不允许这么牛逼的人物存在
条件说明

条件值可以为bool类型的True或是False,也可以是一个其他类型,这个其他类型有值,则代表为True,没有值,则为False.

范例

#有值的字典
condition_has_value = {'red':'#FF0000'}
if condition_has_value:
    print('True')
else:
    print('False')
output:True

#没有值的字典
condition_has_value = {}
if condition_has_value:
    print('True')
else:
    print('False')
output:False
布尔型变量做and or not运算
# a,b 同为bool,则and运算,两个都为真,则返回True,两个有一个不为真,则为返回False
a = True
b = False
condition = a and b
if condition:
    print('a and b is true')
else:
    print('a and b is false')
 output:a and b is false
# a,b 同为bool,则or运算,两个都为假,则返回False,两个有一个不为假,则为返回True
a = True
b = False
condition = a or b
if condition:
    print('a and b is true')
else:
    print('a and b is false')
output:a and b is true
非布尔型变量做and or not运算

返回值

a = {}
b = []
print('a bool value is {}'.format(bool(a)))
print('b bool value is {}'.format(bool(b)))
print('a and b is {}'.format(a and b))
print('a and b is {}'.format(a or b))

output:
a bool value is False
b bool value is False
a and b is {}
a 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值