【发布时间】:2017-07-24 23:51:59
【问题描述】:
这是我目前所拥有的:
import sys
first = float(sys.argv[1])
second = str(sys.argv[2])
third = float(sys.argv[3])
if second == "+":
print first + third
elif second == "-":
print first - third
elif second == "*":
print first * third
elif second == "/":
print first / third
elif second == "^":
print first ** third
else:
print "Invalid Operator"
第一个和第三个参数应该是双浮点数。我不确定该运算符应该如何表示,所以我只是将其命名为“second”并将其设置为字符串。我对我应该如何实际进行计算感到困惑。我的 if/elif/else 语句错了吗?我应该使用“打印”还是“返回”来进行实际计算?
这是一个测试文件的例子:
def test_add(self):
output = self.runScript("simple_calc.py", "1", "+", "1")
result = float(output)
self.assertAlmostEqual(2.0, result, places=10)
output = self.runScript("simple_calc.py", "-1", "+", "1")
result = float(output)
self.assertAlmostEqual(0.0, result, places=10)
output = self.runScript("simple_calc.py", "1.0", "+", "-1.0")
result = float(output)
self.assertAlmostEqual(0.0, result, places=10)
【问题讨论】:
-
您是否遇到任何具体错误?
-
使用 Python 使用
^计算幂的部分将不起作用。在你的代码中使用**。 -
@slackxx,如果您有新错误,请提出新问题,尽管我建议您先尝试调试自己的代码,但不要将它们编辑到您当前的问题中。
-
从其他地方的 cmets 中,我看到您正在学习 Python 初学者课程。不幸的是,对于使用通用编程语言的初学者项目来说,计算器是一个非常糟糕的选择,因为在这种情况下清理和解析任意输入是一项非常困难的任务。
-
@PadraicCunningham 我无法提出新问题。我需要等待 2 天大声笑
标签: python python-2.7