在python

时间:2016-10-23 11:19:28

标签: python python-2.7

这是我到目前为止所做的:

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语句错了吗?我应该使用" print"或"返回"进行实际计算?

这是测试文件的示例:

 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)

3 个答案:

答案 0 :(得分:2)

您使用=代替==

所以应该是这样的

if second =="+":

并为所有

做同样的事情

=是一个赋值语句而不是比较

答案 1 :(得分:0)

例如,您可以创建一个名为calculator的函数,然后将其与用户输入一起使用。 :

def calculator(x, y, operator):
    if operator == "+":
        return x + y
    if operator == "-":
        return x - y
    if operator == "*":
        return x * y
    if operator == "/":
        return x / y

x和y当然是用户输入的数字,运营商是首选的运营商。所以基本上这里的函数需要3个参数。

答案 2 :(得分:0)

这是我的解决方案:

def Operation():    
    while True:
        operation = raw_input('Select operation: \n + = addition\n - = Subtraction\n * = multiplication\n / = Division\n')
        if operation.strip() == '+':
            break
        elif operation.strip() == '-':
            break        
        elif operation.strip() == '*':
            break
        elif operation.strip() == '/':
            break            
        else:
            print "Please select one of the operations"
            continue       
    return operation   

def number():
    while True:    
        try:
            number = int(raw_input("Please enter a number: "))
            break
        except ValueError:
            print "Please enter valid number: "
    return number

num1 = number()
operator = Operation()
num2 = number()

def calculate(num1, operator, num2):
    if operator == "+":
        return num1 + num2
    elif operator == "-": 
        return num1 - num2    
    elif operator == "*": 
        return num1 * num2
    elif operator == "/": 
        return num1 / num2

print calculate(num1, operator, num2)