gpt4 book ai didi

python - 如何在 'for x in range' 语句中压缩 'if' 语句 'elif' 语句中的 'while' 语句

转载 作者:行者123 更新时间:2023-11-28 19:54:09 25 4
gpt4 key购买 nike

我有一个制作数学表的代码,我觉得有可能减少,因为我重复了三个相同的代码,但每个 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)

请告诉我如何压缩这段代码。

最佳答案

你通常会做这样的事情:

  • 将运算符作为函数存储在变量中

  • 使用字典查找运算符

  • 使用 .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)))

关于python - 如何在 'for x in range' 语句中压缩 'if' 语句 'elif' 语句中的 'while' 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39803878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com