目录
1.本节学习内容
理论部分
- 掌握基本的条件,循环语句的使用
- 掌握assert断言break,continue,pass等语句的使用
- 熟悉推导式的用法
练习部分
- 课后思考题
- 龟兔赛跑游戏
2.理论部分笔记整理
条件语句
2.1 if语句
if expression:
expr_true_suite
expression中可以通过布尔操作符and,or和not实现多重条件判断。
2.2 if-else语句
if expression :
expr_true_suite
else
expr_false_suite
2.3 if-elif-else语句
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
.
.
elif expressionN
exprN_true_suite
else:
expr_false_suite
2.4 assert 关键词
assert这个关键词我们称之为“断言”,当这个关键词后边的条件为False时,程序自动崩溃并抛出Assert Error
2.5 while 循环
while expression:
code1
2.6while-else循环
while expression:
code1
else:
code2
2.7 for循环
for 迭代变量 in 可迭代对象:
code
2. 8for-else循环
for 迭代变量 in 可迭代对象:
code1
else:
code2
2.9几个常见的语句
(1)range函数
(2)enumerate函数
(3)break语句
(4)continue语句
(5)pass语句
(6)推导式
3.课后练习题详解
(1)查找那些既可以被7整除又可以被5整除的数字,介于1500和2700之间。
# 循环
nums = []
for num in range(1500, 2700):
if num % 5 == 0 and num % 7 == 0:
nums.append(num)
(2)龟兔赛跑游戏
v1 = int(input('Please input the speed of rabbit:'))
v2 = int(input('Please input the speed of tortoise:'))
t = int(input('Please input the distance between them:'))
s = int(input('Please input the time rabbit wastes for tortoise:'))
l = int(input('Please input the distance of track:'))
l1, l2 = 0, 0
while l1 < l and l2 < l:
if l1-l2 < t:
l1 += v1
l2 += v2
else:
l2 += v2 * s
if l1 > l2:
print('R')
elif l1 < l2:
print('T')
else:
print('D')
print(int(l/v2))