我正在学习Python中的函数,并被要求创建一个脚本,该脚本需要两个输入值,并对它们执行一些数学运算。我编写了下面的代码,但不断收到错误消息,在第17行,我尝试打印答案,'结果'没有定义。我不明白这一点,因为我觉得我在每个函数中定义'结果'。显然,我遗漏了一些与函数和返回值相关的基本概念。任何帮助将不胜感激。
def sum(a,b):
result = a + b
return result
def times(a,b):
result = a * b
return result
def divide(a,b):
result = a / b
return result
def subtract(a,b):
result = a / b
return result
print "Answer is %d" % result
def start():
print "This program can perfom a math function of any two numbers"
a = int(raw_input("Enter first number: "))
b = int(raw_input("Enter second number: "))
c = raw_input("Enter math function you want: ")
if c == "+":
sum(a,b)
elif c == "x":
times(a,b)
elif c == "/":
divide(a,b)
elif c == "-":
subtract(a,b)
else:
print "you didnt enter a function!"
start()
这是错误: 文件“defPrac2.py”,第17行,in 打印“答案是%d”%结果
答案 0 :(得分:2)
看到问题是你没有从启动功能返回任何东西, 再次Python遵循缩进级别,即在第一级写入的任何内容(没有空格的行将首先执行),
从顶部删除行打印行并修改start函数以返回值:
def start():
print "This program can perfom a math function of any two numbers"
a = int(raw_input("Enter first number: "))
b = int(raw_input("Enter second number: "))
c = raw_input("Enter math function you want: ")
res = -1
if c == "+":
res = sum(a,b)
elif c == "x":
res = times(a,b)
elif c == "/":
res = divide(a,b)
elif c == "-":
res = subtract(a,b)
else:
print "you didnt enter a function!"
return res
result = start()
# use format instead of access specifier as it may give you error if
# not handling the specific type case format is more generic
print "Answer is {0}".format(result)
快乐编码:)
答案 1 :(得分:0)
尝试此操作,当您有返回值时,您可以将该值放入新变量中,然后在print语句中打印或直接打印。 `
def sum(a,b):
result = a + b
return result
def times(a,b):
result = a * b
return result
def divide(a,b):
result = a / b
return result
def subtract(a,b):
result = a / b
return result
def start():
print "This program can perfom a math function of any two numbers"
a = int(raw_input("Enter first number: "))
b = int(raw_input("Enter second number: "))
c = raw_input("Enter math function you want: ")
if c == "+":
print("The answer is "+sum(a,b))
elif c == "x":
print("The answer is "+times(a,b))
elif c == "/":
print("The answer is "+divide(a,b))
elif c == "-":
print("The answer is "+subtract(a,b))
else:
print "you didnt enter a function!"
start()
`