分支结构
单向分支结构
分支结构基本语法
if 条件表达式
语句1
语句2
语句3
- 单向分支举个栗子
a = "学习python“
if a:
print("好好学习”)
print("天天向上“)
print("大家加油冲鸭!”)
age = 19
if age >16:
print("喝酒去")
print("下次你请我")
双向分支结构
- if…else…表达式
语法结构:
if 条件表达式:
语句1
语句2
...
else:
语句1
语句2
......
- 双向分支举个栗子
a = " "
if a:
print("好好学习")
print("天天向上")
else:
print("回家种田")
print("学习吧”)
gender = input("请输入您的性别:")
print(gender)
if gender == "man":
print("去浪了")
print("浪里个浪")
else:
print("浪什么浪,睡觉去")
- 栗子来了
score = input("请输入需要查询的成绩:")
score = int(score)
if score > 90:
print("你考得很好啊,小朋友")
if score >= 80 and score <90:
print("还行吧")
if score >= 70 and score <80:
print("凉凉")
if score >= 60 and score <70:
print("终于及格了")
if score <60:
print("天啊,怎么又挂了")
多路分支结构
- 多个分支的情况
语法结构
if 条件表达式:
语句1
....
elif 条件表达式:
语句1
....
elif 条件表达式:
语句1
....
elif 条件表达式:
语句1
....
else:
语句1
......
#elif可以有多个,可根据实际情况
#else可选
#多路分支最多只会执行一种情况
- 升级版栗子
score = input("请输入学生成绩:")
score = int(score)
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("E")
循环结构
循环结构
- 重复执行某一个固定的动作或任务
- 分类
for
while
for循环
语法
for 变量 in 序列:
语句1
语句2
....
- 举个栗子
list_one = [1,2,3,4,5,6,7,8]
for k in list_one:
print(k)
sco_list = ['90','86','78','56',]
for sco in sco_list:
if sco == "90":
print("小盆友,你好优秀")
else:
print("洗洗睡吧,孩子")
for-else语句
- for循环结束时,有时候需要执行一些收尾工作,此时需要使用else语句
- else语句是可选
sco_list = ['90','86','78','56',]
for sco in sco_list:
if sco == "90":
print("小盆友,你好优秀")
else:
print("洗洗睡吧,孩子")
else:
print("一起努力哦!")
break语句
break:无条件结束整个循环,简称循环猝死
- 来个栗子
dig_list = [4,6,8,45,7,89,45]
for dig in dig_list:
if dig == 7:
print("哈哈哈,找到了")
break
else:
print(dig)
continue语句
continue:继续
- 来个栗子
dig_list = [1,2,3,4,5,6,7,8,9]
for dig in dig_list:
if dig % 2 == 0:
continue
print(dig)
print("哈哈哈,找到了")
pass
pass只是占位符,代表这句话啥也不干,也没有跳过功能
- 来个栗子
age = 19
if age >19:
pass
else:
print("你还小")
ages = [2,5,6,12,16,18,34,67]
for age in ages:
pass
print(age)
range函数
- 生成有序数列
- 生成数字队列可以定制
- 来两个栗子
dig_list = range(1,100) # ange包头不包尾
for dig in dig_list:
print(dig)
for i in range(1,10):
print(i)
while循环
- 一个循环语句
- 表示当条件成立时,就循环,适应于不知道具体循环次数,但能确定在某个条件成立的情况下就循环
while语法:
while 条件表达式:
语句块
#另一种表达方式
while 条件表达式:
语句块1
else:
语句块2
- 举个栗子
capital = 10000
year = 0
while capital <20000:
capital = capital * (1 + 0.067)
year += 1
print(year)