课程内容
1、条件判断
2、循环
3、函数
4、类
条件判断
if condition:
do somthing
else:
do somthing
File "<ipython-input-4-ccbf315b7275>", line 2
do somthing
^
SyntaxError: invalid syntax
卖蔬果,合计金额32.5,满30打九折, 求实际花费
total_cost=32.5
if total_cost>30:
discount=0.9
else:
discount=1
total_cost*=discount
print('实际花费为: {}元'.format(total_cost))
实际花费为: 29.25元
卖蔬果,合计金额32.5,满30打九折,满50打8折, 求实际花费
total_cost=60
if total_cost>50:
discount=0.8
elif total_cost>30:
discount=0.9
else:
discount=1
total_cost*=discount
print('实际花费为: {}元'.format(total_cost))
实际花费为: 48.0元
重点
1.条件判断可以任意组合
elif可以有任意多个,else可有可无
条件判断可以嵌套
- condition
condition=('e')
if condition:
print('Ture')
else:
print('False')
Ture
condition=('')
if condition:
print('Ture')
else:
print('False')
False
###从理解的角度来讲,一个值被当作布尔值,概念上更像是有与没有的区别
and or not
##布尔型变量做运算
a=[1,2,3]
b=10
print(a and b)
print(b and a)
print(a or b)
print(b or a)
print(not b)
10
[1, 2, 3]
[1, 2, 3]
10
False
条件判断的近亲-断言
if not condition:
crash program
#意思是:我断言它是肯定是这样的,如果不是,就崩溃
File "<ipython-input-34-46d15215a3c8>", line 2
crash program
^
SyntaxError: invalid syntax
age=18
assert age==20,"他居然不是20岁"
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-37-334d2b7cb1eb> in <module>
1 age=18
----> 2 assert age==20,"他居然不是20岁"
AssertionError: 他居然不是20岁
age=18
assert age==18
循环
for遍历循环,while 条件循环
costs=(3,6,7)
for cost in costs:
print('消费{}元'.format(str(cost).center(10)))
消费 3 元
消费 6 元
消费 7 元
###长度为20的随机列表
import random
random.randint(1,10)
6
import random
random_numbers=[]
while len(random_numbers)<20:
random_numbers.append(random.randint(1,10))
print(random_numbers,len(random_numbers))
[3, 4, 7, 9, 7, 8, 6, 3, 6, 5, 2, 9, 6, 7, 3, 8, 5, 2, 6, 6] 20
编程建议,能用for循环,就不用while循环
random_numbers=[]
for i in range(20):
random_numbers.append(random.randint(1,10))
print(random_numbers,len(random_numbers))
[10, 7, 5, 3, 5, 10, 8, 3, 8, 5, 7, 2, 5, 9, 10, 4, 10, 3, 1, 1] 20
循环条件跟数量没关系时,只能用while
###题目:往空裂帛添加随即数,直到添加的为9,则终止
random_numbers=[]
while (9 not in random_numbers):
random_numbers.append(random.randint(1,10))
print(random_numbers,len(random_numbers))
[10, 5, 2, 1, 5, 1, 5, 9] 8
###重点:只有一个元素的列表
###问题[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m4TdYN5l-1571494145620)(attachment:image.png)]
a=[1]
b=(2,)
type(a),type(b),b,len(b)
(list, tuple, (2,), 1)
a=[1]
b=(2)
type(a),type(b)
(list, int)
random_numbers
[10, 5, 2, 1, 5, 1, 5, 9]