你的课本希望你尝试在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
是一个函数;而函数总是产生一个返回值,这样它们就可以用在表达式中,如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"
'A =开方(25);打印的(a);' – rlms