《零基础学Python》Python的控制语句【三】

整体文章目录

整体目录

一、 当前章节目录

在这里插入图片描述

二、结构化程序设计

  1. 结构化程序设计是进行以模块功能和处理过程设计为主的详细设计的基本原则。结构化程序设计是过程式程序设计的一个子集,它对写入的程序使用逻辑结构,使得理解和修改更有效更容易。
  2. 结构化程序设计的三种基本结构是:顺序结构、判断结构和循环结构。

三、条件判断语句

  • 条件语句是指根据条件表达式的不同计算结果,使程序流转至不同的代码快。

3.1 if条件语句

x = input("x:")
x = int(x)
x = x + 1
# 执行if语句内的程序
a = input("a:")
a = int(a)
b = input("b:")
b = int(b)
if(a > b):
    print(a, " > ", b)
else:
    print(a, " < ", b)

运行结果:

a:2
b:3
2 < 3

3.2 if…elif…else 判断语句

# if elif else语句
score = float(input("score:"))      # 接收用户输入并将其转换为float类型,当输入为小数时,使用int转换会报错
if 90 <= score <= 100:
    print("A")
elif 80 <= score <90:
    print("B")
elif 60 <= score <80:
    print("C")
else:
    print("D")

运行结果:

score:85
B

3.3 if语句也可以嵌套

x = -1
y = 99
if(x >= 0):
    if(x > 0):
        y = 1           # 嵌套的if语句
    else:
        y = 0
else:
    y = -1
print("y = ", y)

运行结果:

score:85
B

3.4 switch语句的替代方案

# 使用字典实现switch语句
from __future__ import division                # 导入division模块
x = 1
y = 2
operator = "/"
result = {                                      # 定义字典
    "+": x + y,
    "-": x - y,
    "*": x * y,
    "/": x / y
}
print(result.get(operator))

运行结果:

0.5

class switch(object):                           # 定义switch类
    def __init__(self , value):                 # 初始化需要匹配的值value
        self.value = value
        self.fall = False                       # 如果匹配到的case语句中没有break,则fall为True

    def __iter__(self):                         # 定义__iter__()方法
        yield self.match                        # 调用match方法 返回一个生成器
        raise StopIteration                     # 用StopIteration异常来判断for循环是否结束

    def match(self , *args):                    # 模拟case子句的方法
        if self.fall or not args:               # 如果fall为True,则继续执行下面的case子句
                                                # 或case子句没有匹配项,则流转到默认分支
            return True
        elif self.value in args:                # 匹配成功
            self.fall = True
            return True
        else:                                   # 匹配失败
            return  False

operator = "+"
x = 1
y = 2
for case in switch(operator):                   # switch只能用于for…in…循环中
    if case('+'):
        print(x + y)
        break
    if case('-'):
        print(x - y)
        break
    if case('*'):
        print(x * y)
    if case('/'):
        print(x / y)
    if case():                             # 默认分支
        print("")

运行结果:

3

四、循环语句

  • 循环语句是指重复执行同一段代码块,通常用于遍历集合或者累加计算。

4.1 while循环

# while循环
numbers = input("输入几个数字,用逗号分隔:").split(",")
print(numbers)
x = 0
while x < len(numbers):                             # 当x的值小于输入字数的个数的时候,执行循环内容
    print(numbers[x])
    x += 1                                          # 一个循环结束时给x加1

运行结果:

输入几个数字,用逗号分隔:4,5,2
[‘4’, ‘5’, ‘2’]
4
5
2

# 带else子句的while循环
x = float(input("输入x的值:"))
i = 0
while(x != 0):
    if(x > 0):
        x -= 1
    else:
        x += 1
    i = i + 1
    print("第%d次循环:%f" % (i, x))
else:
    print("x等于0:", x)

运行结果:

输入x的值:10
第1次循环:9.000000
第2次循环:8.000000
第3次循环:7.000000
第4次循环:6.000000
第5次循环:5.000000
第6次循环:4.000000
第7次循环:3.000000
第8次循环:2.000000
第9次循环:1.000000
第10次循环:0.000000
x等于0: 0.0

4.2 for循环

# for in 语句
for x in range(-1, 2):
    if x > 0:
        print("正数:", x)
    elif x == 0:
        print("零:", x)
    else:
        print("负数:", x)
else:
    print("循环结束")

运行结果:

负数: -1
零: 0
正数: 1
循环结束

for x in range(0,5,2):
    print(x)

运行结果:

0
2
4

4.3 break和continue语句

x = int(input("输入x的值:"))
y = 0
for y in range(0 , 100):
    if x == y:
        print("找到数字:", x)
        break
else:
    print("没有找到")

运行结果:

输入x的值:10
找到数字: 10

x = 0
for i in [1, 2, 3, 4, 5]:
    if x == i:
        continue
    x += i
print("x的值为", x)

运行结果:

x的值为 12

五、结构化程序示例

# 冒泡排序
def bubbleSort(numbers):                        # 冒泡算法的实现
    for j in range(1,len(numbers)):             # 循环语句负责设置冒泡排序进行的次数
        for i in range(len(numbers) - j):       # i为列表的下标
            if numbers[i] > numbers[i + 1]:     # 把数值小的数字放到顶端
                numbers[i],numbers[i + 1] = numbers[i + 1] , numbers[i]
            print(numbers)

def main():                                     # 主函数
    numbers = [23 , 12 , 9 , 15 , 6]            # 定义numbers列表
    bubbleSort(numbers)                         # 调用bubbleSort函数

if __name__ == '__main__':
    main()

运行结果:

[12, 23, 9, 15, 6]
[12, 9, 23, 15, 6]
[12, 9, 15, 23, 6]
[12, 9, 15, 6, 23]
[9, 12, 15, 6, 23]
[9, 12, 15, 6, 23]
[9, 12, 6, 15, 23]
[9, 12, 6, 15, 23]
[9, 6, 12, 15, 23]
[6, 9, 12, 15, 23]

六、习题

习题:

  1. Python中的break和continue语句有什么区别?分别在什么情况下使用?
  2. 使用结构化编程思想实现冒泡排序。
  3. 以下是个人所得税的缴纳标准:
    1)税额为1~5000元,包括5000元,适用的个人所得税税率为0%;
    2)税额为5000~8000元,包括8000元,适用的个人所得税税率为3%;
    3)税额为8000~17000元,包括17000元,适用的个人所得税税率为10%;
    4)税额为17000~30000元,包括30000元,适用的个人所得税税率为20%;
    5)税额为30000~40000元,包括40000元,适用的个人所得税税率为25%;
    6)税额为40000~60000元,包括60000元,适用的个人所得税税率为30%;
    7)税额为60000~85000元,包括85000元,适用的个人所得税税率为35%;
    8)税额为85000元以上的,适用的个人所得税税率为45%;
    编写程序,输入收入金额,输出需要缴纳的个人所得税以及扣除所得税后的实际个人收入。

答案:

  1. break语句可以使程序跳出循环语句,从而执行循环体之外的程序。即break语句可以提前结束循环。
    continue语句也是用来跳出循环的语句,但是与break不同的是,使用 continue语句不会跳出整个循环体,只是跳出当前的循环,然后继续执行后面的循环。
  2. 代码见 五、结构化程序示例
  3. 代码如下。
score = float(input("score:"))
if 85000 < score:
    print("个人所得税:" , score*0.45, "实际个人收入:", score - score*0.45)
elif 60000 < score <=85000:
    print("个人所得税:" , score*0.35, "实际个人收入:", score - score*0.35)
elif 40000 < score <= 60000:
    print("个人所得税:", score * 0.30, "实际个人收入:", score - score * 0.30)
elif 30000 < score <= 40000:
    print("个人所得税:", score * 0.25, "实际个人收入:", score - score * 0.25)
elif 17000 < score <= 30000:
    print("个人所得税:", score * 0.20, "实际个人收入:", score - score * 0.20)
elif 8000 < score <= 17000:
    print("个人所得税:", score * 0.10, "实际个人收入:", score - score * 0.10)
elif 5000 < score <= 8000:
    print("个人所得税:", score * 0.03, "实际个人收入:", score - score * 0.03)
elif 1 < score <= 5000:
    print("个人所得税:", score * 0, "实际个人收入:", score - score * 0)
else:
    pass

运行结果:

score:16000
个人所得税: 1600.0 实际个人收入: 14400.0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值