您的教科书希望您尝试interactive interpreter 中的内容,它会在您输入值时显示您的值。这是一个外观示例:
$ python
Python 2.7.5+ (default, Sep 17 2013, 17:31:54)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def sqrt(n):
... approx = n/2.0
... better = (approx + n/approx)/2.0
... while better != approx:
... approx = better
... better = (approx + n/approx)/2.0
... return approx
...
>>> sqrt(25)
5.0
>>>
这里的关键是表达式和语句之间的区别。 def 是一个语句,不会产生任何结果。 sqrt,def 块定义的,是一个函数;并且函数总是产生一个返回值,这样它们就可以在表达式中使用,比如sqrt(25)。如果您的函数不包含return 或yield,则此值为None,解释器会忽略它,但在这种情况下,sqrt 返回一个自动打印的数字(并存储在名为_ 的变量中)。在脚本中,您可以将最后一行替换为 print sqrt(25) 以获取终端的输出,但返回值的有用之处在于您可以进行进一步处理,例如 root=sqrt(25) 或 print sqrt(25)-5。
如果我们要运行与脚本完全相同的行,而不是在交互模式下,则没有隐式打印。 sqrt(25) 行被接受为表达式的语句,这意味着它已被计算 - 但随后该值被简单地丢弃。它甚至没有进入_(相当于计算器的Ans 按钮)。通常我们将它用于导致副作用的函数,例如quit(),它会导致 Python 退出。
顺便说一句,print 在 Python 2 中是一个语句,但在 Python 3 中是一个函数。这就是为什么它越来越多地使用括号。
这是一个依赖sqrt(在本例中为 Python 自己的版本)返回值的脚本:
from math import sqrt
area = float(raw_input("Enter a number: "))
shortside = sqrt(area)
print "Two squares with the area", area, "square meters,",
print "placed side to side, form a rectangle", 2*shortside, "meters long",
print "and", shortside, "meters wide"