文章目录
环境安装
python基础
条件判断
描述
条件判断可描述为:
- 如果满足条件condition_1,则执行语句statement_1,否则执行statement_other
- 如果满足条件condition_1,则执行语句statement_1,如果不满足条件condition_1而满足条件condition_2,则执行语句statement_2,如果不满足条件condition_1和condition_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
表示如果condition为False,则输出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