Appendix C. Solutions to Exercises
This appendix contains solutions to the exercises that appear at the end of each chapter.
Interaction. Assuming your Python is configured properly, you should participate in an interaction that looks something like this:
%
python
copyright information lines... >>>"Hello World!"
'Hello World!' >>> # <Ctrl-D or Ctrl-Z to exit>Programs. Here’s what your code (i.e., module) file and shell interactions should look like:
%
cat module1.py
print 'Hello module world!' %python module1.py
Hello module world!Modules. The following interaction listing illustrates running a module file by importing it. Remember that you need to reload it to run again without stopping and restarting the interpreter. The bit about moving the file to a different directory and importing it again is a trick question: if Python generates a module1.pyc file in the original directory, it uses that when you import the module, even if the source code file (.py) has been moved to a directory not on Python’s search path. The .pyc file is written automatically if Python has access to the source file’s directory and contains the compiled bytecode version of a module. We look at how this works in more detail in Chapter 5.
%
python
>>>import module1
Hello module world! >>>Scripts. Assuming your platform supports the
#!
trick, your solution will look like the following (though your#!
line may need to list another path on your machine):%
cat module1.py
#!/usr/local/bin/python (or ...
Get Learning Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.