【Python编程基础-2】条件循环结构

目录

1.本节学习内容

2.理论部分笔记整理

2.1 if语句

2.2 if-else语句

2.3 if-elif-else语句

2.4 assert 关键词

2.5 while 循环

2.6while-else循环

2.7 for循环

2. 8for-else循环

2.9几个常见的语句

3.课后练习题详解


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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值