【发布时间】:2015-12-26 04:33:45
【问题描述】:
我是 Python 新手 - 用 PHP、javascript 编写过一些脚本,但我不是程序员(尽管我是一名技术作家,具有记录 API 等经验,因此非常广泛的“被动”编程知道如何)。:
在此处执行以下步骤:https://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Functions。具体看链接re:简单的计算器程序
想知道我是否可以通过以列表形式存储用于不同计算的所有组件来减少程序的冗余,然后通过使用用户的菜单选项来处理任何计算请求的非常简单、通用的方法列表中的索引。我假设以这种方式构造事物是一种很好的形式,但不知道!原始教程显然更具可读性,但意味着需要对每个小“if”块重复执行相同的错误检查......
无论如何,我不知道如何将实际计算存储为列表中的元素。那可能吗?据我所知……我设法封装并调用列表中的一些细节,但仍然必须为每个单独的计算执行一系列“if”语句。
(对不起,如果这些问题是基本的。。我进行了一堆搜索,但没有找到明确的文档:这里是你可以捕获的所有内容,但无法以列表形式捕获)所以 - 我的链接到代码的变体:
#simple calculator program
# Prompts for possible calculations
add = ["Add this: ", "to this: ", "+"]
subtract = ["Subtract this: ", "from this: ", "-"]
multiply = ["Multiply this: ", "by this: ", "*"]
divide = ["Divide this: ", "by this: ", "/"]
# List of possible calculations
calcPrompts = [add, subtract, multiply, divide]
def promptEntries(Arg):
try:
op1 = int(input(Arg[0]))
op2 = int(input(Arg[1]))
operator = (Arg[2])
return op1, op2, operator
except:
print("Invalid entry. Please try again.")
choice = 0
#This variable tells the loop whether it should loop or not.
# 1 means loop. Anything else means don't loop.
loop = 1
while loop == 1:
#Display the available options
print ("\n\nCalculator options are:")
print (" ")
print ("1) Addition")
print ("2) Subtraction")
print ("3) Multiplication")
print ("4) Division")
print ("5) Quit calculator.py")
print (" ")
try:
choice = int(input("Choose your option: "))
choice = choice - 1
op1, op2, operator = promptEntries(calcPrompts[choice])
print(op1, operator, op2, "=", end=" ")
if choice == 0:
print(op1 + op2)
elif choice == 1:
print(op1 - op2)
elif choice == 2:
print(op1 * op2)
elif choice == 3:
if op2 != 0:
print(op1 / op2)
else:
print("Division by zero is invalid, please try again.")
elif choice == 4:
loop = 0
print ("Thank you for using calculator.py")
except:
print("invalid entry, please try again.")
【问题讨论】: