You are on page 1of 32

What is the difference between a library and a package?

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

The draw module may look something like this:

 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

In this example, the game module imports the draw module, which enables it to use functions


implemented in that module. The main function would use the local function play_game to run the
game, and then draw the result of the game using a function implemented in the draw module
called draw_game. To use the function draw_game from the draw module, we would need to specify
in which module the function is implemented, using the dot operator. To reference
the draw_game function from the game module, we would need to import the draw module and only
then call draw.draw_game().
When the import draw directive will run, the Python interpreter will look for a file in the directory
which the script was executed from, by the name of the module with a .py prefix, so in our case it will
try to look for draw.py. If it will find one, it will import it. If not, he will continue to look for built-in
modules.
You may have noticed that when importing a module, a .pyc file appears, which is a compiled Python
file. Python compiles files into Python bytecode so that it won't have to parse the files each time
modules are loaded. If a .pyc file exists, it gets loaded instead of the .py file, but this process is
transparent to the user.
Importing module objects to the current namespace
We may also import the function draw_game directly into the main script's namespace, by using
the from command.

 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

Extending module load path


There are a couple of ways we could tell the Python interpreter where to look for modules, aside from
the default, which is the local directory and the built-in modules. You could either use the
environment variable PYTHONPATH to specify additional directories to look for modules in, like
this:

 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

  

def add(x, y):

    return (x+y)

  

def subtract(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

Python Modules vs Packages |


Differences Between Python
Modules and Packages
BY DATAFLAIR TEAM · UPDATED · SEPTEMBER 26, 2018

1. Python Modules vs Packages


In our article on Python Modules vs Packages, we discussed what they are,
and saw how to create our own. We also saw where they are located in our
file system. But throughout the article, we saw a lot of similarities to
modules. Hence, we dedicate this article to Differences Between Python
Modules and Packages.

Python Modules vs Packages

2. What is Python Modules?


A module is a Python file containing Python statements and definitions. For
example, a file evenodd.py is a module, and we call it ‘evenodd’. We put
similar code together in one module. This helps us modularize our code,
and make it much easier to deal with. And not only that, a module grants us
reusability. With a module, we don’t need to write the same code again for a
new project that we take up.

In our previous article, we created a module evenodd in package two. This


is what evenodd.py holds:

1. def check():
2. a=int(input('Enter a number'))
3. if a%2==0: print("Even")
4. else: print("Odd")

a. How to Import a Python Module?


So, as you can see, a module simply contains Python code. Consequently,
we can import it, like a package.

1. >>> import one.two.evenodd


2. >>>

To call function check(), we do the following:

1. >>> from one.two.evenodd import check


2. >>> check()

Enter a number7
Odd

1. >>>

Another example would be the constants ‘pi’ and ‘e’ from the ‘math’
module.

1. >>> import math


2. >>> from math import pi
3. >>> math.pi

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. >>>

Let’s update evenodd.py to have two functions- check and evenodd.

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 *:

1. >>> from one.two.evenodd import *


2. >>> check()

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

c. Reloading a Python Module


A module is imported only once. This is for efficiency purposes. Let’s add
this code to evenodd.py:

1. print("Loading evenodd")
2. num=7

Now, let’s restart the shell, and import evenodd thrice.

1. >>> import one.two.evenodd

Loading evenodd

1. >>> import one.two.evenodd


2. >>> import one.two.evenodd

See? It imported it only once. Because of this, Python gives us a function to


let us reload the module when we want to. This is in the module ‘imp’.

1. >>> import imp


2. >>> imp.reload(one.two.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)

[‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’,


‘__name__’, ‘__package__’, ‘__spec__’, ‘add’, ‘check’ , ‘num’]
We saw this function when we talked about the Built-in Functions in
Python.
3. What is Python Packages?
A package, in essence, is like a directory holding subpackages and modules.
While we can create our own packages, we can also use one from the
Python Package Index (PyPI) to use for our projects.

To import a package, we type the following:

import Game.Sound.load

We can also import it giving it an alias:

import Game.Sound.load as load game

You can’t import a function using the dot operator(.) For that, you must
type this:

from Game.Sound.load import volume_up

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.

To get a deeper insight into packages, check Python Packages.

4. Differences Between Python Modules


and Packages
So, now that we’ve revised both modules and packages, let’s see how they
differ:

1. A module is a file containing Python code. A package, however, is like


a directory that holds sub-packages and modules.
2. A package must hold the file __init__.py. This does not apply to
modules.
3. To import everything from a module, we use the wildcard *. But this
does not work with packages.
This was all about the article on Python Modules vs Packages

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.

Furthermore, if you have any query, feel free to approach us!

his set of MySQL Multiple Choice Questions & Answers (MCQs) focuses on “The group
by & having Clause”.

1. What is the meaning of “GROUP BY” clause in Mysql?


a) Group data by column values
b) Group data by row values
c) Group data by column and row values
d) None of the mentioned
View Answer
Answer: a
Explanation: None.

2. Which clause is similar to “HAVING” clause in Mysql?


a) SELECT
b) WHERE
c) FROM
d) None of the mentioned
View Answer
Answer: b
Explanation: “WHERE” is also used to filter the row values in Mysql.

3. What is the meaning of “HAVING” clause in Mysql?


a) To filter out the row values
b) To filter out the column values
c) To filter out the row and column values
d) None of the mentioned
View Answer
Answer: a
Explanation: None.

4. “COUNT” keyword belongs to which categories in Mysql?


a) Aggregate functions
b) Operators
c) Clauses
d) All of the mentioned
View Answer
Answer: a
Explanation: None.

5. Which among the following belongs to an “aggregate function”?


a) COUNT
b) UPPER
c) LOWER
d) All of the mentioned
View Answer
Answer: a
Explanation: None.

6. Which of the following belongs to an “aggregate function”?


a) COUNT
b) SUM/AVG
c) MIN/MAX
d) All of the mentioned
View Answer
Answer: d
Explanation: None.

7. Which clause is used with an “aggregate functions”?


a) GROUP BY
b) SELECT
c) WHERE
d) Both GROUP BY and WHERE
View Answer
Answer: a
Explanation: “GROUP BY” is used with aggregate functions.

8. What is the significance of the statement “GROUP BY d.name” in the following


MySQL statement?

SELECT d.name, COUNT (emp_id) emp_no


FROM department d INNER JOIN Employee e
ON d.dept_id=e.emp_id
GROUP BY d.name

a) Aggregation of the field “name” of both table


b) Aggregation of the field “name” of table “department”
c) Sorting of the field “name”
d) None of the mentioned
View Answer
Answer: b
Explanation: “GROUP BY” clause s used for aggregation of field.

9. What is the significance of the statement “HAVING COUNT (emp_id)>2” in the


following MySQL statement?

SELECT d.name, COUNT (emp_id) emp_no


FROM department d INNER JOIN Employee e
ON d.dept_id=e.emp_id
GROUP BY d.name
HAVING COUNT (emp_id)&gt;2

a) Filter out all rows whose total emp_id below 2


b) Selecting those rows whose total emp_id>2
c) Filter out all rows whose total emp_id below 2 & Selecting those rows whose total
emp_id>2
d) None of the mentioned
View Answer
Answer: c
Explanation: “HAVING” clause are worked similar as “WHERE” clause.

Sanfoundry Global Education & Learning Series – MySQL Database.

Example of SQL Statement using HAVING


Consider the following Sale table.

oid order_name previous_balance custome

11 ord1 2000 Alex

12 ord2 1000 Adam

13 ord3 2000 Abhi

14 ord4 1000 Adam

15 ord5 2000 Alex


Suppose we want to find the customer whose previous_balance sum is more
than 3000.
We will use the below SQL query,
SELECT *

FROM sale GROUP BY customer

HAVING sum(previous_balance) > 3000

I am going to consider the following table to explain to you the examples:

EmpID EmpName EmpEmail PhoneNumber Salary City


1 Nidhi nidhi@sample.com 9955669999 50000 Mumbai
2 Anay anay@sample.com 9875679861 55000 Pune
3 Rahul rahul@sample.com 9876543212 35000 Delhi
4 Sonia sonia@sample.com 9876543234 35000 Delhi
5 Akash akash@sample.com 9866865686 25000 Mumbai
Let us take a look at each one of them.

Use SQL GROUP BY on single column


Example: 
Write a query to retrieve the number of employees in each city.

1 SELECT COUNT(EmpID), City

2 FROM Employees

3 GROUP BY City;

Use SQL GROUP BY on multiple columns


Example: 
Write a query to retrieve the number of employees having different salaries in each
city.

1 SELECT City, Salary, Count(*)

2 FROM Employees

3 GROUP BY City, Salary;

se SQL GROUP BY with ORDER BY


When we use the SQL GROUP BY statement with the ORDER BY clause, the
values get sorted either in ascending or descending order.

Example: 
Write a query to retrieve the number of employees in each city, sorted in descending
order.

1 SELECT COUNT(EmpID), City


2 FROM Employees

3 GROUP BY City

4 ORDER BY COUNT(EmpID) DESC;

Use SQL GROUP BY with HAVING clause


The SQL GROUP BY statement is used with ‘HAVING’ clause to mention conditions
on groups. Also, since we cannot use the aggregate functions with the WHERE
clause, we have to use the ‘HAVING’ clause to use the aggregate functions with
GROUP BY.

 Example: 
Write a query to retrieve the number of employees in each city, having salary >
15000

1 SELECT COUNT(EmpID), City

2 FROM Employees

3 GROUP BY City

4 HAVING SALARY > 15000;

Use GROUP BY with JOINS


JOINS are SQL statements used to combine rows from two or more tables, based on
a related column between those tables. We can use the  SQL GROUP BY statement
to group the result set based on a column/ columns. Consider the below tables to
execute the JOIN statements with the SQL GROUP BY clause.

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:

1 SELECT Clients.ClientName, COUNT(Projects.ProjectID) AS RequestedProjects FRO

2 LEFT JOIN Clients ON Projects.ProjectID = Clients.ProjectID


3 GROUP BY ClientName;

Output:
The table will have the following data:

L DBA Certification Training


Weekday / Weekend BatchesSee Batch Details

ClientName RequestedProjects

Arun 1
Rohan 1
Sanjana 1

Consider the CUSTOMERS table having the following records.


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

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;

This would produce the following result −


+----+--------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
+----+--------+-----+---------+---------+
Python Questions and Answers – Python Modules
« Prev

Next »
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Python
Modules”.

1. Which of these definitions correctly describes a module?


a) Denoted by triple quotes for providing the specification of certain program elements
b) Design and implementation of specific functionality to be incorporated into a program
c) Defines the specification of how it is to be used
d) Any program that reuses code
View Answer
Answer: b
Explanation: The term “module” refers to the implementation of specific functionality to
be incorporated into a program.

2. Which of the following is not an advantage of using modules?


a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks
c) Provides a means of reducing the size of the program
d) Provides a means of testing individual parts of the program
View Answer
Answer: c
Explanation: The total size of the program remains the same regardless of whether
modules are used or not. Modules simply divide the program.

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.

5. Which of the following is true about top-down design process?


a) The details of a program design are addressed before the overall design
b) Only the details of the program are addressed
c) The overall design of the program is addressed before the details
d) Only the design of the program is addressed
View Answer
Answer: c
Explanation: Top-down design is an approach for deriving a modular design in which the
overall design.

6. In top-down design every module is broken into same number of submodules.


a) True
b) False
View Answer
Answer: b
Explanation: In top-down design every module can even be broken down into different
number of submodules.

7. All modular designs are because of a top-down design process.


a) True
b) False
View Answer
Answer: b
Explanation: The details of the program can be addressed before the overall design too.
Hence, all modular designs are not because of a top-down design process.

8. What will be the output of the following Python code?

#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]

d) There is a name clash


View Answer
Answer: d
Explanation: A name clash is when two different entities with the same identifier become
part of the same scope. Since both the modules have the same function name, there is a
name clash.

9. Which of the following isn’t true about main modules?


a) When a python file is directly executed, it is considered main module of a program
b) Main modules may import any number of modules
c) Special name given to main modules is: __main__
d) Other main modules can import main modules
View Answer
Answer: d
Explanation: Main modules are not meant to be imported into other modules.

10. Which of the following is not a valid namespace?


a) Global namespace
b) Public namespace
c) Built-in namespace
d) Local namespace
View Answer
Answer: b
Explanation: During a Python program execution, there are as many as three
namespaces – built-in namespace, global namespace and local namespace.

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.

12. Which of the following is false about “from-import” form of import?


a) The syntax is: from modulename import identifier
b) This form of import prevents name clash
c) The namespace of imported module becomes part of importing module
d) The identifiers in module are accessed directly as: identifier
View Answer
Answer: b
Explanation: In the “from-import” form of import, there may be name clashes because
names of the imported identifiers aren’t specified along with the module name.

13. Which of the statements about modules is false?


a) In the “from-import” form of import, identifiers beginning with two underscores are
private and aren’t imported
b) dir() built-in function monitors the items in the namespace of the main module
c) In the “from-import” form of import, all identifiers regardless of whether they are
private or public are imported
d) When a module is loaded, a compiled version of the module with file extension .pyc is
automatically produced
View Answer
Answer: c
Explanation: In the “from-import” form of import, identifiers beginning with two
underscores are private and aren’t imported.

14. What will be the output of the following Python code?


from math import factorial
print(math.factorial(5))
a) 120
b) Nothing is printed
c) Error, method factorial doesn’t exist in math module
d) Error, the statement should be: print(factorial(5))
View Answer
Answer: d
Explanation: In the “from-import” form of import, the imported identifiers (in this case
factorial()) aren’t specified along with the module name.

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.

You might also like