(一)IF语句
avg = 90
math = 95
Chinese = 85
if math < Chinese:
print("语文更好!")
if math>Chinese:
print("数学更好!")
Chinese +=5
if avg == Chinese:
print("语文跟平均分相等")
数学更好!
语文跟平均分相等
附加练习
1、你认为 if 对它下面的代码起什么作用?
答:进行条件判断。
2、为什么 if 下面的代码要缩进 4 个空格?
答:方便理解,解释运行逻辑
3、如果没有缩进会发生什么?
答:报错
5、如果你改变 people,cats 和 dogs 的初始值会发生什么?
答:初始值变了,对应的if语句里的条件判断出的结果就会不同。
avg = 90
Chinese = 90
if avg < Chinese:
print("语文更好!")
elif avg > Chinese:
print("语文不好!")
else:
print("不知道谁好~")
不知道谁好~
如果多个 elif 块都是 True 会发生什么?
答:从上到下运行,它只会运行第一个
print("天堂和地狱,你只有一次选择,左还是右,请输入!")
print("-------------------------------------------------------")
door = input("")
if door == "左":
print("恭喜,进入了通往天堂的第一关,接下来你将看到2个箱子,1号箱,2号箱,请选一个")
box = input("")
if box == "1":
print("你将获得重生的机会")
elif box == "2":
print("继续往前走")
else:
print("请遵守游戏规则")
elif door =="右":
print("很遗憾,地狱的大门已经打开,你将遭受万鬼的噬咬!")
else:
print("-------------------------------------------------------")
print("""无知小儿,天堂和地狱都不走吗?
想的倒挺美!
你已经成功引起了的我注意,请小心!""")
天堂和地狱,你只有一次选择,左还是右,请输入!
-------------------------------------------------------
哈哈哈哈哈哈哈哈
-------------------------------------------------------
无知小儿,天堂和地狱都不走吗?
想的倒挺美!
你已经成功引起了的我注意,请小心!
(二)FOR语句
count_list = [1,2,3,4,5]
kemu = ["语文","数学","外语","物理"]
# 获取list 的各个元素
for num in count_list:
print(f'这只是在测试for循环{num}')
print("-------------------------------------------------------")
for km in kemu:
print(f'我正在学的科目是{km}')
print("-------------------------------------------------------")
ele = []
for i in count_list:
ele.append(i)
print(ele)
这只是在测试for循环1
这只是在测试for循环2
这只是在测试for循环3
这只是在测试for循环4
这只是在测试for循环5
-------------------------------------------------------
我正在学的科目是语文
我正在学的科目是数学
我正在学的科目是外语
我正在学的科目是物理
-------------------------------------------------------
[1, 2, 3, 4, 5]
(三)while语句
i = 0
numbers = []
while i < 6:
print(f"At the top i is {i}")
numbers.append(i)
i = i + 1
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
At the top i is 0
Numbers now: [0]
At the bottom i is 1
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5
分支和函数