4.控制流if-else

通过 if-else 语句来做决定程序运行的流程

一、实验目的

  • if 语句
  • else 语句
  • 真值检测

二、知识要点

1.if-elif-else基本语法
1
2
3
4
5
6
7
8
if 判断条件1:
执行语句1……
elif 判断条件2:
执行语句2……
elif 判断条件3:
执行语句3……
else:
执行语句4……

三、实验内容

1.示例程序
  • 代码:
1
2
3
4
5
6
7
8
9
10
11
a = int(input("Please input an integer:"))
b = int(input("Please input an integer:"))
c = int(input("Please input an integer:"))
if a:
print("a is true")
elif b:
print("b is true")
elif c:
print("c is true")
else:
print("All false")
  • 结果:
a b c print
0 0 0 all false
0 0 1 c is ture
0 1 0 b is true
0 1 1 b is true
1 0 0 a is true
1 0 1 a is true
1 1 0 a is true
1 1 1 a is true

可以看出,在控制流if-else中每块语句都是独立的,按照代码顺序执行,出现true程序块结束,出现false则继续进行下一条语句,如果一直是false到程序块末尾之后执行下一个程序块。(不为零的任何值都为真)

2.真值检测

通常我们使用:

1
2
if x:
pass

而无需使用:
1
2
if x == True:
pass

四、实验结果

1.员工工资问题

一企业进行年终奖发放,员工底薪5000元,员工年贡献利润在10000到20000之间的抽成10%,贡献利润在20000以上的抽成20%,其余情况不抽成,你需要输入员工利润X,程序计算应发年终奖并输出。(结果精确到分)

  • 代码:
1
2
3
4
5
6
7
X = float(input("Please input the profit:"))
if X > 20000:
print("The awards is:", "{:.2f}".format(5000 + X * 0.2))
elif X < 1000:
print("The awards is:", "{:.2f}".format(5000))
else:
print("The awards is:", "{:.2f}".format(5000 + X * 0.1))
  • 结果:
1
2
3
4
5
6
7
8
Please input the profit:100000
The awards is: 25000.00

Please input the profit:12000
The awards is: 6200.00

Please input the profit:200
The awards is: 5000.00

下一篇:3.运算符和表达式
上一篇:5.循环
目 录:Python学习

本文标题:4.控制流if-else

文章作者:小哲

发布时间:2020年03月06日 - 19:16

最后更新:2020年03月30日 - 11:36

原始链接: 点击复制原始链接

许可协议: 协议-转载请保留原文链接及作者