我有一个生成数学表的代码,我觉得有可能减少,因为我有三个相同的代码重复,但每个if / elif语句只有略微不同的解决方案。
num=10
x=str(input("Enter Math Operation (+, -, *): "))
while (x != "+" and x != "-" and x != "*"):
x=str(input("\tEnter Math Operation: "))
if x=="+":
for table in range(1,11):
print(str(num),str(x),table,"=",num+table)
elif x=="-":
for table in range(1,11):
print(str(num),str(x),table,"=",num-table)
elif x=="*":
for table in range(1,11):
print(str(num),str(x),table,"=",num*table)
请告诉我如何压缩此代码。
答案 0 :(得分:6)
您通常会这样做:
将操作符存储为变量
使用字典查找运算符
使用.format()
代替将大量字符串拼凑在一起
如果参数已经是字符串
str()
以下是这样的:
import operator
x = 10
operators = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
}
while True:
op_name = input('Enter Math Operation ({}): '.format(', '.join(operators)))
op_func = operators.get(op_name)
if op_func is not None:
break
for y in range(1, 11):
print('{} {} {} = {}'.format(x, op_name, y, op_func(x, y)))
答案 1 :(得分:2)
您可以使用查找表来存储不同的功能
num=10
x=str(input("Enter Math Operation (+, -, *): "))
while (x != "+" and x != "-" and x != "*"):
x=str(input("\tEnter Math Operation: "))
ops = {
'+': lambda x, y: x+y,
'-': lambda x, y: x-y,
'*': lambda x, y: x*y}
fn = ops[x]
for table in range(1,11):
print(str(num),str(x),table,"=",fn(num,table))
答案 2 :(得分:2)
函数是python中的第一类对象。将正确的函数分配给变量,然后使用它。
num=10
x=str(input("Enter Math Operation (+, -, *): "))
# Read operation
while (x != "+" and x != "-" and x != "*"):
x=str(input("\tEnter Math Operation: "))
# Select appropriate function
if x=="+":
op = lambda x, y : x + y
elif x=="-":
op = lambda x, y : x - y
elif x=="*":
op = lambda x, y : x * y
# Use function
for table in range(1,11):
val = op(num, table)
print(str(num), str(x),table,"=", val)