python - 我可以从 print 语句调用 Python 中的函数吗?

标签 python python-2.7 function

我是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/

相关文章:

python - 如何使用异步 for 循环遍历列表?

django - HTTP/1.0 301永久移动-Django

c - 如何在 C 中对数据数组执行函数

c++ - 如何在函数内部访问 Mat 类型参数的变量名

python - Pyparsing packrat会降低性能

python - 如何找到并单击带有 Selenium 的隐藏按钮?

python - 使用 Python 子进程时,为什么 Ctrl-C 不会产生与 kill -2 相同的行为?

python-2.7 - 使用 python 从 netCDF 读取时间序列

python - 获取 'package' 和 'endpackage' 可选字符串之外的结构名称列表

c - 在宏或函数之间切换