Your textbook expects you to try things in the interactive interpreter, which shows you values as you enter them. Here's an example of how this looks:
$ 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
>>>
The key thing here is the difference between expressions and statements. def
is a statement, and produces no result. sqrt
, which the def
block defines, is a function; and functions always produce a return value, such that they can be used in expressions, like sqrt(25)
. If your function doesn't contain return
or yield
this value is None
, which the interpreter ignores, but in this case sqrt returned a number which is automatically printed (and stored in a variable called _
). In a script, you might replace the last line with print sqrt(25)
to get the output to a terminal, but the useful thing about return values is that you can do further processing, such as root=sqrt(25)
or print sqrt(25)-5
.
If we were to run the exact same lines as a script, instead of in interactive mode, there is no implicit printing. The line sqrt(25)
is accepted as a statement of an expression, which means it's calculated - but then the value is simply discarded. It doesn't even go into _
(which is the equivalent of the calculator's Ans button). Normally we use this for functions that cause side effects, like quit()
, which causes Python to exit.
By the way, print
is a statement in Python 2 but a function in Python 3. That's why more and more uses of it have parenthesis.
Here is a script which relies on sqrt
(in this case Python's own version) returning a value:
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"