Added questions to writing python scripts.
Objective Questions
-------------------
1. Which of the following variables contains the locations to search for
python modules
a. sys.pythonpath
#. sys.path
#. os.pythonpath
#. os.path
Answer: sys.path
2. What is the type of ``sys.path``
a. list of strings
#. list of int
#. string
#. tuple of strings
Answer: list of strings
3. The script ``utils.py`` is in one of locations of PYTHONPATH and contains
the following code:
def show(x):
print x
show("Hello World")
if __name__ == "__main__":
show("Hello Test")
How do you import the file.
a. import utils
#. import utils.py
#. import /home/user/utils
#. import /home/user/utils.py
Answer: import utils
4. The script ``utils.py`` is in one of locations of PYTHONPATH and contains
the following code:
def show(x):
print x
show("Hello World")
if __name__ == "__main__":
show("Hello Test")
How do you use the ``show`` function after doing ``import utils``
a. utils.show("hey")
#. show("hey")
#. utils.py.show("hey")
#. utils.py.show.py("hey")
Answer: utils.show("hey")
5. The script ``utils.py`` is in one of locations of PYTHONPATH and contains
the following code:
def show(x):
print x
show("Hello World")
if __name__ == "__main__":
show("Hello Test")
How do you use the ``show`` function after doing ``from utils import show``
a. utils.show("hey")
#. show("hey")
#. utils.py.show("hey")
#. utils.py.show.py("hey")
Answer: show("hey")
5. The script ``utils.py`` is in one of locations of PYTHONPATH and contains
the following code:
def show(x):
print x
show("Hello World")
if __name__ == "__main__":
show("Hello Test")
What is printed when you do ``import utils``
Answer::
Hello World
6. The script ``utils.py`` is in one of locations of PYTHONPATH and contains
the following code:
def show(x):
print x
show("Hello World")
if __name__ == "__main__":
show("Hello Test")
What is printed when the script is executed.
Answer::
Hello World
Hello Test
7. Say, we wish to use the ``pi`` value from the ``math`` module in
the standard library. How do we import it?
Answer: from math import pi OR import math.pi OR
import math.pi as pi
8. A module should contain only functions, True or False?
Answer: False.
Larger Questions
----------------
1. Look at the python documentation (from the web) and learn how to
make a folder containing some python files into a module.
Answer: Add a file named __init__.py
2. We know that ``sys.path`` has the paths in which Python checks for
a module, when it is imported. Suppose you have a package ``utils``
in some location on your disk, which is not on the python path, how
will you import it?
Answer: Append that path to the ``sys.path`` variable.