不同于其他语言,python中没有switch case语句,关于为什么没有,官方的解释是这样的
python 需要实现类似switch-case功能就需要自定义函数或类来处理
使用字典配合函数
- 直接取值
复制代码
1
2
3
4
5
6
7
8
9
10
11def foo(var): return { 'a': 1, 'b': 2, 'c': 3, }.get(var, 0) #0为找不到默认返回值,相当于处理default,可自设置 calcer = input("输入:") result = [foo(i) for i in calcer] print(result)
输入cabk,输出
复制代码
1
2[3, 1, 2, 0]
- 使用lambda完成对应的功能
lambda只适用于做简单的功能,如果需要做复杂的运算最好另外定义函数
模拟计算器小例子(没有做优先级判断,按顺序执行)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30import re from functools import reduce # 简单的lambda函数实现 switch_dict = { "*": lambda x, y: x * y, "+": lambda x, y: x + y, "-": lambda x, y: x - y, "/": lambda x, y: x / y, "%": lambda x, y: x % y, "<": lambda x, y: min(x, y), ">": lambda x, y: max(x, y)} def switch_case(flags, values): n = values[0][0] if isinstance(values[0], tuple) else values[0] # 计算步数,为了方便提取符号 x = int(values[0][1] if isinstance(values[0], tuple) else n) # 第一次之后values变成自身返回的tuple y = int(values[1]) return n+1, switch_dict[flags[n]](x, y) if __name__ == '__main__': flag = rf"[{''.join(switch_dict.keys())}]" while 1: src = input("输入计算式:") flags = re.findall(flag, src) values = re.split(flag, src) result = reduce(lambda x, y: switch_case(['+'] + flags, (x, y)), values, 0) #步数初始化为0,计算次数多了一次加0 print(f'{src}: 对数据{values}经过{result[0]-1}步{flags}计算获得最终结果:{result[1]}')
输入2+3*4/5+1,输出
复制代码
1
22+3*4/5+1:对数据['2', '3', '4', '5', '1']经过4步['+', '*', '/', '+']计算获得最终结果:5
使用类
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54import string class Switch: def __init__(self, value): self.value = value self.fall = False def __iter__(self): """Return the match method once, then stop""" yield self.match raise StopIteration def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: return True elif self.value in args: self.fall = True return True else: return False # 数字转大写 def case_CapNum(src): for case in Switch(src): if case('1'): print('壹'); break if case('2'): print('贰'); break if case('3'): print('叁'); break if case('4'): print('肆'); break if case('5'): print('伍'); break if case('6'): print('陆'); break if case('7'): print('柒'); break if case('8'): print('捌'); break if case('9'): print('玖'); break if case('0'): print('零'); break if case(): print('不是单数字,请重新输入') # 判断是什么类型字符 def case_what(src): for case in Switch(src): if case(*string.ascii_lowercase): print(f'{src}: 小写字母第{ord(src)-96}个'); break if case(*string.ascii_uppercase): print(f'{src}: 大写字母{ord(src)-64}个'); break if case(*string.digits): print(f'{src}: "数字"'); break if case(*string.whitespace): print(f'{src}: "空格"'); break if case(*string.punctuation): print(f'{src}: "符号"'); break if case(): print('不是单字符,请重新输入') if __name__ == '__main__': while 1: case_CapNum(input('输入一个数:')) case_what(input('输入一个字符:'))
运行效果
复制代码
1
2
3
4
5
6
7
8
9输入一个数:4 肆 输入一个字符:e e: 小写字母第5个 输入一个数:12 不是单数字,请重新输入 输入一个字符:, ,: "符号"
最后
以上就是玩命唇膏最近收集整理的关于python-小知识点 ---switch-case 模拟计算器的全部内容,更多相关python-小知识点 ---switch-case 模拟计算器内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复