我是Python新手,正在探索。现在,在下面的代码中,我尝试从 print 语句调用函数,这合法吗?
# My func
def summer(num1,num2):
print "The summation of the numbers is: %d " % (num1+num2)
num1 = raw_input("Enter a number: ")
num2 = raw_input("Enter another number: ")
print "Again, the summation: %d " % (summer(num1,num2))
print "That is the end of the program."
现在就到了
print "Again, the summation: %d " % (summer(num1,num2))
有效吗?我收到错误。
我可以用这种方式从字符串调用函数吗?谢谢。
我得到的错误是:
Traceback (most recent call last):
File "myfunc.py", line 9, in <module>
summer(num1,num2)
File "myfunc.py", line 3, in summer
print "The summation of the numbers is: %d " % (num1+num2)
TypeError: %d format: a number is required, not str
最佳答案
您需要缩进方法中的代码,并返回一个字符串。您还需要将字符串转换为整数:
def summer(num1,num2):
return "The summation of the numbers is: %d " % (int(num1)+int(num2))
num1 = raw_input("Enter a number: ")
num2 = raw_input("Enter another number: ")
print "Again, the summation: %s " % (summer(num1,num2))
print "That is the end of the program."
关于python - 我可以从 print 语句调用 Python 中的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41763718/