我是新手尝试使用LPTH学习python。我试图以不同的方式做运动21。我没有将值放在变量中,而是要求用户输入值。
def add(a,b):
print "Add %d and %d." %(a,b)
print a+b
def substract (a,b):
print "Substract %d from %d." %(a,b)
print a-b
def multiply (a,b):
print "Multiply %d*%d." %(a,b)
print a*b
def divide (a,b):
print "Dividing %d and %d." %(a,b)
print a/b
total_age_of_the_class = add(int(raw_input(">")) , int(raw_input(">")))
#height_difference = substract (int(raw_input("Ram's height:"), int(raw_input("Shyam's height:"))))
height = substract (78,4)
weight = multiply (90,2)
iq = divide (100,2)
print "Age:%d, height:%d, weight:%d, iq:%d" %(total_age_of_the_class, height, weight, iq)
由于某种原因,当代码运行代码的最后一行时会抛出错误。 在此先感谢您的帮助。
答案 0 :(得分:3)
你应该返回你的功能的结果,而不是打印它们:
def substract (a,b):
print "Substract %d from %d." %(a,b)
return a-b
def multiply (a,b):
print "Multiply %d*%d." %(a,b)
return a*b
def divide (a,b):
print "Dividing %d and %d." %(a,b)
return a/b
如果没有return statement,Python函数始终返回默认值None
。这意味着当你到达这里时:
height = substract (78,4)
weight = multiply (90,2)
iq = divide (100,2)
height
,weight
和iq
都将分配给None
,这会导致字符串格式化操作因您的错误而失败。