if condition:
do something
else:
do something
应用题:小姐姐买水果,合计金额32.5元,水果店搞活动,满30打九折,求小姐姐的实际花费?
In [1]:total_cost = 32.5
if total_cost > 30:
discount = 0.9
else:
discount = 1
total_cost *= discount
print('小姐姐的实际花费为:{}元'.format(total_cost))
小姐姐的实际花费为:29.25元
应用题:如果购买水果超过30元打九折,超过50元,打8折,求小姐姐的实际花费?
In [2]: total_cost = 52
if total_cost > 50:
discount = 0.8
elif 30 < total_cost <50:
discount = 0.9
else:
discount = 1
total_cost *= discount
print('小姐姐的实际花费为:{}元'.format(total_cost))
小姐姐的实际花费为:41.6元
重点
1.条件判断可以任意组合
第一层意思:elif可以由0~任意多个,else可有可无
第二次意思:条件判断可以进行嵌套
2.着重看一下condition
In [3]:bool(''), bool({}), bool([])
Out[3]:(False, False, False)
In [4 ]: condition = ' '
if condition:
print('True')
else:
print('False')
Out[4]:False
从理解的角度来讲,一个值被当做布尔值,概念上更像是有与没有的区别
布尔型变量做运算
In [5]:a = True
b = False
print('a and b is {}'.format(a and b))
print('a or b is {}'.format(a or b))
Out[5]:a and b is False
a or b is True
非布尔型变量做and or not 运算(返回2个变量中的一个类型)
In [6]:a = 'hello world'
b = {1,2,3} #若b = [ ] , 返回 a and b is [ ]
print('a and b is {}'.format(a and b))
print('a or b is {}'.format(a or b))
Out[6]:a and b is {1, 2, 3}
a or b is hello world
In [7]:a = ' ' # 空字符代表False
b = {1,2,3}
print(bool(b))
print('a and b is {}'.format(a and b))
print('a or b is {}'.format(a or b)) # a空,所以判断b,b为True,则返回b的值
Out[7]:True
a and b is
a or b is [1,2,3]
In [8]:
#非布尔型变量做and 运算
a =[1,2,3]
b = 10
print(b and a)
#非布尔型变量 or 运算
a = 'ni hao'
b = {'apple':100}
print(a or b)
#非布尔型变量not 运算,永远返回True/False
print(not b)
Out[8]:[1, 2, 3]
ni hao
False
#非布尔型变量not 运算,永远返回True/False
In [9]:not 'zaf'
Out[9]:False
In [10]:not []
Out[10]:True
条件判断的近亲--断言(一般程序员自我筛查时使用)if not condition:
crash program
# 即断言它肯定是这样的,否则,崩溃
# 断言正确,不输出结果
In[11]:
age = 18
assert age == 18
# 断言错误,输出AssertionError
In[12]:
age = 19
assert age == 18
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-19-071d61ae2e14> in <module>() 1 age = 19 ----> 2 assert age == 18 AssertionError:
In[13]:
age = 19
assert age == 18,'他竟然不是18岁'
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-20-7cfa3ac6daa0> in <module>() 1 age = 19 ----> 2 assert age == 18,'他竟然不是18岁' AssertionError: 他竟然不是18岁