Professional Documents
Culture Documents
2 Answers
Joshua Etim, B.Sc Computer Engineering & Software Engineering, Obafemi Awolowo University
(2021)
Answered Oct 24, 2019
According to my knowledge, I’ll try to explain what I know about the two.
For simplification, I will use examples.
A standard package is usually for a particular task. A good example is the nodemon package for
NodeJs/Express.
The nodemon package automatically restarts the server after saving changes, so you don’t have to go
through the process over again. That’s what a package does: help you with specific tasks during a
development process.
The language a package is written in can be the same for which it runs on or it could be in
combination with other languages.
Now for a library, a good example is jQuery. Now, when you think of jQuery, you know there are
many functions you can use it for. It is more or less a group of javascript functions chunked together
in one file, to make it faster when coding in Javascript.
That’s what a library does: group functions of a language in one file, and then give you custom
functions to call, making the coding process faster for you.
Modules and Packages
In programming, a module is a piece of software that has a specific functionality. For example, when
building a ping pong game, one module would be responsible for the game logic, and
another module would be responsible for drawing the game on the screen. Each module is a different
file, which can be edited separately.
Writing modules
Modules in Python are simply Python files with a .py extension. The name of the module will be the
name of the file. A Python module can have a set of functions, classes or variables defined and
implemented. In the example above, we will have two files, we will have:
script.py
1
2
3
mygame/
mygame/game.py
mygame/draw.py
IPython Shell
In [1]:
Run
Powered by DataCamp
The Python script game.py will implement the game. It will use the function draw_game from the
file draw.py, or in other words, thedraw module, that implements the logic for drawing the game on
the screen.
Modules are imported from other modules using the import command. In this example,
the game.py script may look something like this:
script.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# game.py
# import the draw module
import draw
def play_game():
...
def main():
result = play_game()
draw.draw_game(result)
# this means that if this script is executed, then
# main() will be executed
if __name__ == '__main__':
main()
IPython Shell
In [1]:
Run
Powered by DataCamp
script.py
1
2
3
4
5
6
7
# draw.py
def draw_game():
...
def clear_screen(screen):
...
IPython Shell
In [1]:
Run
Powered by DataCamp
script.py
1
2
3
4
5
6
7
# game.py
# import the draw module
from draw import draw_game
def main():
result = play_game()
draw_game(result)
IPython Shell
In [1]:
Run
Powered by DataCamp
You may have noticed that in this example, draw_game does not precede with the name of the module
it is imported from, because we've specified the module name in the import command.
The advantages of using this notation is that it is easier to use the functions inside the current module
because you don't need to specify which module the function comes from. However, any namespace
cannot have two objects with the exact same name, so the import command may replace an existing
object in the namespace.
Importing all objects from a module
We may also use the import * command to import all objects from a specific module, like this:
script.py
1
2
3
4
5
6
7
# game.py
# import the draw module
from draw import *
def main():
result = play_game()
draw_game(result)
IPython Shell
In [1]:
Run
Powered by DataCamp
This might be a bit risky as changes in the module might affect the module which imports it, but it is
shorter and also does not require you to specify which objects you wish to import from the module.
Custom import name
We may also load modules under any name we want. This is useful when we want to import a module
conditionally to use the same name in the rest of the code.
For example, if you have two draw modules with slighty different names - you may do the following:
script.py
1
2
3
4
5
6
7
8
9
10
11
12
13
# game.py
# import the draw module
if visual_mode:
# in visual mode, we draw using graphics
import draw_visual as draw
else:
# in textual mode, we print out text
import draw_textual as draw
def main():
result = play_game()
# this can either be visual or textual depending on
visual_mode
draw.draw_game(result)
IPython Shell
In [1]:
Run
Powered by DataCamp
Module initialization
The first time a module is loaded into a running Python script, it is initialized by executing the code in
the module once. If another module in your code imports the same module again, it will not be loaded
twice but once only - so local variables inside the module act as a "singleton" - they are initialized
only once.
This is useful to know, because this means that you can rely on this behavior for initializing objects.
For example:
script.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# draw.py
def draw_game():
# when clearing the screen we can use the main screen
object initialized in this module
clear_screen(main_screen)
...
def clear_screen(screen):
...
class Screen():
...
# initialize main_screen as a singleton
main_screen = Screen()
IPython Shell
In [1]:
Run
Powered by DataCamp
script.py
1
PYTHONPATH=/foo python game.py
IPython Shell
In [1]:
Run
Powered by DataCamp
This will execute game.py, and will enable the script to load modules from the foo directory as well as
the local directory.
Another method is the sys.path.append function. You may execute it before running
an import command:
script.py
1
sys.path.append("/foo")
IPython Shell
In [1]:
Run
Powered by DataCamp
This will add the foo directory to the list of paths to look for modules in as well.
Exploring built-in modules
Check out the full list of built-in modules in the Python standard library here.
Two very important functions come in handy when exploring modules in Python -
the dir and help functions.
If we want to import the module urllib, which enables us to create read data from URLs, we
simply import the module:
script.py
1
2
3
4
5
# import the library
import urllib
# use it
urllib.urlopen(...)
IPython Shell
In [1]:
Run
Powered by DataCamp
We can look for which functions are implemented in each module by using the dir function:
script.py
1
2
3
4
5
6
7
8
9
10
11
>>> import urllib
>>> dir(urllib)
['ContentTooShortError', 'FancyURLopener', 'MAXFTPCACHE',
'URLopener', '__all__', '__builtins__',
'__doc__', '__file__', '__name__', '__package__',
'__version__', '_ftperrors', '_get_proxies',
'_get_proxy_settings', '_have_ssl', '_hexdig', '_hextochr',
'_hostprog', '_is_unicode', '_localhost',
'_noheaders', '_nportprog', '_passwdprog', '_portprog',
'_queryprog', '_safe_map', '_safe_quoters',
'_tagprog', '_thishost', '_typeprog', '_urlopener',
'_userprog', '_valueprog', 'addbase', 'addclosehook',
'addinfo', 'addinfourl', 'always_safe', 'basejoin', 'c',
'ftpcache', 'ftperrors', 'ftpwrapper', 'getproxies',
'getproxies_environment', 'getproxies_macosx_sysconf', 'i',
'localhost', 'main', 'noheaders', 'os',
'pathname2url', 'proxy_bypass', 'proxy_bypass_environment',
'proxy_bypass_macosx_sysconf', 'quote',
'quote_plus', 'reporthook', 'socket', 'splitattr',
'splithost', 'splitnport', 'splitpasswd', 'splitport',
IPython Shell
In [1]:
Run
Powered by DataCamp
When we find the function in the module we want to use, we can read about it more using
the help function, inside the Python interpreter:
script.py
1
help(urllib.urlopen)
IPython Shell
In [1]:
Run
Powered by DataCamp
Writing packages
Packages are namespaces which contain multiple packages and modules themselves. They are simply
directories, but with a twist.
Each package in Python is a directory which MUST contain a special file called __init__.py. This file
can be empty, and it indicates that the directory it contains is a Python package, so it can be imported
the same way a module can be imported.
If we create a directory called foo, which marks the package name, we can then create a module
inside that package called bar. We also must not forget to add the __init__.py file inside
the foo directory.
To use the module bar, we can import it in two ways:
script.py
1
import foo.bar
IPython Shell
In [1]:
Run
Powered by DataCamp
or:
script.py
1
from foo import bar
IPython Shell
In [1]:
Run
Powered by DataCamp
In the first method, we must use the foo prefix whenever we access the module bar. In the second
method, we don't, because we import the module to our module's namespace.
The __init__.py file can also decide which modules the package exports as the API, while keeping
other modules internal, by overriding the __all__ variable, like so:
script.py
1
2
3
__init__.py:
__all__ = ["bar"]
IPython Shell
In [1]:
Run
Powered by DataCamp
Exercise
In this exercise, you will need to print an alphabetically sorted list of all functions in the re module,
which contain the word find.
script.py
1
2
3
import re
# Your code goes here
IPython Shell
In [1]:
SolutionRun
Powered by DataCamp
This site is generously supported by DataCamp. DataCamp offers online interactive Python
Tutorials for Data Science. Join over a million other learners and get started learning Python for data
science today!
Python Modules
A module is a file containing Python definitions and statements. A module can define
functions, classes and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use.
Example:
filter_none
edit
play_arrow
brightness_4
# A simple module, calc.py
return (x+y)
return (x-y)
The import statement
We can use any Python source file as a module by executing an import statement in
some other Python source file.
When interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the
interpreter searches for importing a module. For example, to import the module
calc.py, we need to put the following command at the top of the script :
# importing module calc.py
import calc
print add(10, 2)
Output:
12
The from import Statement
Python’s from statement lets you import specific attributes from a module.
The from .. import .. has the following syntax :
filter_none
edit
play_arrow
brightness_4
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print sqrt(16)
print factorial(6)
Output:
4.0
720
The dir() function
The dir() built-in function returns a sorted list of strings containing the names defined
by a module. The list contains the names of all the modules, variables and functions
that are defined in a module.
filter_none
edit
play_arrow
brightness_4
# Import built-in module random
import random
print dir(random)
Output:
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random',
'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill',
'_BuiltinMethodType', '_MethodType', '__all__',
'__builtins__', '__doc__', '__file__', '__name__',
'__package__', '_acos', '_ceil', '_cos', '_e', '_exp',
'_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random',
'_sin', '_sqrt', '_test', '_test_generator', '_urandom',
'_warn', 'betavariate', 'choice', 'division',
'expovariate', 'gammavariate', 'gauss', 'getrandbits',
'getstate', 'jumpahead', 'lognormvariate', 'normalvariate',
'paretovariate', 'randint', 'random', 'randrange',
'sample', 'seed', 'setstate', 'shuffle', 'triangular',
'uniform', 'vonmisesvariate', 'weibullvariate']
Code Snippet illustrating python built-in modules:
filter_none
edit
play_arrow
brightness_4
# importing built-in module math
import math
# using square root(sqrt) function contained
# in math module
print math.sqrt(25)
# using pi function contained in math module
print math.pi
# 2 radians = 114.59 degreees
print math.degrees(2)
# 60 degrees = 1.04 radians
print math.radians(60)
# Sine of 2 radians
print math.sin(2)
# Cosine of 0.5 radians
print math.cos(0.5)
# Tangent of 0.23 radians
print math.tan(0.23)
# 1 * 2 * 3 * 4 = 24
print math.factorial(4)
# importing built in module random
import random
# printing random integer between 0 and 5
print random.randint(0, 5)
# print random floating point number between 0 and 1
print random.random()
# random number between 0 and 100
print random.random() * 100
List = [1, 4, True, 800, "python", 27, "hello"]
# using choice function in random module for choosing
# a random element from a set such as a list
print random.choice(List)
# importing built in module datetime
import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print time.time()
# Converts a number of seconds to a date object
print date.fromtimestamp(454554)
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
1970-01-06
1. def check():
2. a=int(input('Enter a number'))
3. if a%2==0: print("Even")
4. else: print("Odd")
Enter a number7
Odd
1. >>>
Another example would be the constants ‘pi’ and ‘e’ from the ‘math’
module.
3.141592653589793
1. >>> math.e
2.718281828459045
We can also import using an alias or using the from..import statement, like
we do with packages. To import everything from a module, we do the
following:
1. >>> from math import *
2. >>> e
2.718281828459045
1. >>> pi
3.141592653589793
1. >>>
1. def check():
2. a=int(input('Enter a number'))
3. if a%2==0: print("Even")
4. else: print("Odd")
5. def add(a,b):
6. return a+b
Now, if we want to import all functions from module evenodd, we can just
use the wildcard *:
Enter a number0
Even
1. >>> add(3,4)
b. Search Path
When we import a module, the interpreter first looks in the
current directory. Then, it looks into PYTHONPATH, an environment
variable with a list of directories. Finally, it looks into the installation-
dependent default directory.
1. >>> import sys
2. >>> for i in sys.path:
3. print(i)
C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\Lib\idlelib
C:\Users\lifei\AppData\Local\Programs\Python\Python36-
32\python36.zip
C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\DLLs
C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\lib
C:\Users\lifei\AppData\Local\Programs\Python\Python36-32
C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\lib\site-
packages
1. print("Loading evenodd")
2. num=7
Loading evenodd
Loading evenodd
<module ‘one.two.evenodd’ from
‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-
32\\lib\\site-packages\\one\\two\\evenodd.py’>
d. dir()
Finally, dir() will let us check the components of a module.
1. >>> dir(one.two.evenodd)
import Game.Sound.load
You can’t import a function using the dot operator(.) For that, you must
type this:
A package must have the file __init__.py, even if you leave it empty.
But when we import a package, only its immediate modules are imported,
not the sub-packages. If you try to access those, it will raise an
AttributeError.
5. Conclusion
Now that we know what subtle differences exist between a module and a
package, let’s take up a challenge and take up a project of our own. Let’s do
this to test our package skills? Okay.
his set of MySQL Multiple Choice Questions & Answers (MCQs) focuses on “The group
by & having Clause”.
2 FROM Employees
3 GROUP BY City;
2 FROM Employees
Example:
Write a query to retrieve the number of employees in each city, sorted in descending
order.
3 GROUP BY City
Example:
Write a query to retrieve the number of employees in each city, having salary >
15000
2 FROM Employees
3 GROUP BY City
Projects Table:
ProjectID EmpID ClientID ProjectDate
2345 1 4 26-01-2019
9876 2 5 28-02-2019
3456 3 6 12-03-2019
Clients Table:
ClientID ClientName
4 Sanjana
5 Rohan
6 Arun
Example
Write a query to list the number of projects requested by each client:
Output:
The table will have the following data:
ClientName RequestedProjects
Arun 1
Rohan 1
Sanjana 1
Following is an example, which would display a record for a similar age count that
would be more than or equal to 2.
SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;
Next »
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Python
Modules”.
3. Program code making use of a given module is called a ______ of the module.
a) Client
b) Docstring
c) Interface
d) Modularity
View Answer
Answer: a
Explanation: Program code making use of a given module is called the client of the
module. There may be multiple clients for a module.
4. ______ is a string literal denoted by triple quotes for providing the specifications of
certain program elements.
a) Interface
b) Modularity
c) Client
d) Docstring
View Answer
Answer: d
Explanation: Docstring used for providing the specifications of program elements.
#mod1
def change(a):
b=[x*2 for x in a]
print(b)
#mod2
def change(a):
b=[x*x for x in a]
print(b)
from mod1 import change
from mod2 import change
#main
s=[1,2,3]
change(s)
a) [2,4,6]
b) [1,4,9]
c)
[2,4,6]
[1,4,9]
11. Which of the following is false about “import modulename” form of import?
a) The namespace of imported module becomes part of importing module
b) This form of import prevents name clash
c) The namespace of imported module becomes available to importing module
d) The identifiers in module are accessed as: modulename.identifier
View Answer
Answer: a
Explanation: In the “import modulename” form of import, the namespace of imported
module becomes available to, but not part of, the importing module.
15. What is the order of namespaces in which Python looks for an identifier?
a) Python first searches the global namespace, then the local namespace and finally the
built-in namespace
b) Python first searches the local namespace, then the global namespace and finally the
built-in namespace
c) Python first searches the built-in namespace, then the global namespace and finally
the local namespace
d) Python first searches the built-in namespace, then the local namespace and finally the
global namespace
View Answer
Answer: b
Explanation: Python first searches for the local, then the global and finally the built-in
namespace.