这个程序应该是一个计算器。当我运行程序时,它打印操作
我不知道如何解决这个问题。我一直试图制作一个简单的计算器,在终端上运行几天,但似乎没有任何效果。我想我需要重新定义操作var来打印它。我不知道该怎么做。
#The functions of this program #
def add(num1, num2):
return (num1 + num2)
def sub(num1,num2):
return (num1 - num2)
def mul(num1, num2):
return (num1 * num2)
def div(num1, num2):
return (num1 / num2)
##The variables of this program ##
num1 = input ("Number 1: ")
num2 = input ("Number 2: ")
operation = input ("Operation: ")
###The if statements of this program ###
if operation == "add":
(num1 + num2)
elif operation == "sub":
(num1 - num2)
elif operation == "mul":
(num1 * num2)
elif operation == "div":
(num1 / num2)
####The final code to print the product ####
print operation
答案 0 :(得分:1)
您未在if
声明
if operation == "add":
print(add(num1, num2))
elif operation == "sub":
print(sub(num1, num2))
elif operation == "mul":
print(mul(num1, num2))
elif operation == "div":
print(div(num1, num2))
另请注意,您可以使用dict
来抓取该功能并对其进行评估
ops = {'add': add,
'sub': sub,
'mul': mul,
'div': div}
if operation in ops:
print(ops[operation](num1, num2))
else:
print('Invalid operator requested')
答案 1 :(得分:0)
您的代码中存在一些问题:
input
返回字符串)。raw_input
代替input
。解决方案:
#The functions of this program #
def add(num1, num2):
return (num1 + num2)
def sub(num1,num2):
return (num1 - num2)
def mul(num1, num2):
return (num1 * num2)
def div(num1, num2):
return (num1 / num2)
##The variables of this program ##
num1 = float(raw_input("Number 1: ")) # convert the input to float
num2 = float(raw_input("Number 2: ")) # convert the input to float
operation = raw_input("Operation: ")
# The result variable, it holds an error message, in case the use inputs another operation
result='Unsupported operation'
###The if statements of this program ###
if operation == "add":
result = add(num1, num2)
elif operation == "sub":
result = sub(num1, num2)
elif operation == "mul":
result = mul(num1, num2)
elif operation == "div":
result = div(num1, num2)
####The final code to print the product ####
print result
答案 2 :(得分:0)
这就是你需要的.............
python 3和以下代码
确保您使用的是python3而不是python
e.g。 root @Windows-Phone:〜$ python3 anyName.py
#The functions of this program
def add(num1, num2):
return (num1 + num2)
def sub(num1,num2):
return (num1 - num2)
def mul(num1, num2):
return (num1 * num2)
def div(num1, num2):
return (num1 / num2)
#The variables of this program
num1 = int(input ("Number 1: "))
num2 = int(input ("Number 2: "))
operation = input ("Operation: ")
#The if statements of this program
if operation == "add":
print(add(num1, num2))
if operation == "sub":
print(sub(num1 ,num2))
if operation == "mul":
print(mul(num1,num2))
if operation == "div":
print(div(num1,num2))