好的,所以我在主要调用4函数时遇到了一些问题。我一直坐在这里一个多小时,无法理解。
我继续收到此错误:
(total) = total(num, num2)
UnboundLocalError: local variable 'total' referenced before assignment
def main():
num = float(input(" Enter a number: "))
num2 = float(input(" Enter another number: "))
(total) = total(num, num2)
(diff) = difference(num, num2)
(product) = product(num, num2)
(quot) = quotient(num, num2)
print(" The total is: ", format(total, ".1f"), sep="")
print(" The difference is: ", format(diff, ".1f"), sep="")
print(" The product is: ", format(product, ".2f"), sep="")
print(" The quotient is: ", format(quot, ".2f"), sep="")
def total(num, num2):
total = (num + num2)
return(total)
def difference(num, num2):
diff = abs(num - num2)
return(diff)
def product(num, num2):
product = num * num2
return(product)
def quotient(num, num2):
quot = num / num2
return(quot)
main()
答案 0 :(得分:0)
您的函数描述了您要执行的操作,如果您甚至不使用它们,则没有理由在函数中创建局部变量。
def total(num, num2):
return num+num2
def difference(num, num2):
return abs(num - num2)
def product(num, num2):
return num*num2
def quotient(num, num2):
return num/num2
def main():
num = float(input(" Enter a number: "))
num2 = float(input(" Enter another number: "))
summa = total(num, num2) #try to not use the same name for a variable and a function
diff = difference(num, num2)
prod = product(num, num2)
quot = quotient(num, num2)
print(" The total is: ", format(summa, ".1f"), sep="")
print(" The difference is: ", format(diff, ".1f"), sep="")
print(" The product is: ", format(prod, ".2f"), sep="")
print(" The quotient is: ", format(quot, ".2f"), sep="")
main()