importsysprint(sys.version)# note that the following line causes what looks like error text to appear...sys.exit()print("Is this really the end????")print("Even before this!")
the name of the module actually corresponds to a python file
Python looks in the current working folder (as well as several other locations) for a file named after the module your importing
imagine placing the contents of that file directly into the file you're working on (at the point of the import statement)
An Example Module
In fact, we can make our own modules! We'll take a look at this later, but to illustrate how modules work, we can create two files in the same directory:
foo.py (the module that we'll import)
hello.py
# foo.pyprint("called from inside the foo module")defgreet():print("hi")# hello.pyimportfooprint("hello")foo.greet()
An Example Module Continued
What do you think will be output when we run hello.py? →
insidemy_awesome_modulehello42
Um… So Where Are All of Those Other Modules?
Where do sys, math, random, and other modules come from? If modules are just files, we should just be able to find them!
the current directory
or a list of specified directories called the PYTHON_PATH
these usually vary by system, but
for example, on OSX (Mountain Lion) and Python 3.3, you may be able to find modules in:
# for me/usr/local/Cellar/python3/3.3.2/Frameworks/Python.framework/Versions/3.3/lib/python3.3/# for you.../System/Library/Frameworks/Python.framework/Versions/...
Why Do Modules Exist?
That's great, but why bother with using and/or creating modules (aside, of course, from bringing in additional built-in functionality)?
they encourage code reuse (DRY - don't repeat yourself)
they provide "namespacing" to avoid name collisions
they provide a way of organizing code
Three Modules Out of ??? / HALP!
There are many more modules to explore. Check out the official documentation for a more comprehensive list. You'll find modules like:
you can also check out the python docs in IDLE (go to Help→Python Docs)
you can fiddle around in the interactive shell
* dir()
* help()
>>> import math
>>> help(math)
>>> dir(math)
How About a Practical Application, PLZ?
Rewrite our guess number game so that it uses a random number instead of a hardcoded one. It should display the correct answer after you guess.→
# Run 1:
Guess a number between 1 and 10!
> 5
Nope, I was thinking of 10.
# Run 2:
Guess a number between 1 and 10!
> 8
You guessed right; I was thinking of 8.