chapter 6 modules
chapter 6 modules
chapter 6 modules
return (x+y)
return (x-y)
When the 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.
Syntax of Python Import
import module
Note: This does not import the functions or classes directly instead imports the
module only. To access the functions inside the module the dot(.) operator is
used.
Importing modules in Python
Now, we are importing the calc that we created earlier to perform add operation.
# importing module calc.py
import calc
print(calc.add(10, 2))
Output:
12
Here, we are importing specific sqrt and factorial attributes from the math module.
# module math
# are required.
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
Import all Names
The * symbol used with the from import statement is used to import all the names
from a module to a current namespace.
Syntax:
from module_name import *
The use of * has its advantages and disadvantages. If you know exactly what you
will be needing from the module, it is not recommended to use *, else do so.
# module math
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0
720
# module math
import math as mt
# if we simply do "import math", then
# are required.
print(mt.sqrt(16))
print(mt.factorial(6))
Output
4.0
720
import math
# in math module
print(math.sqrt(25))
print(math.pi)
print(math.degrees(2))
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
print(math.cos(0.5))
print(math.tan(0.23))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
import random
print(random.randint(0, 5))
print(random.random())
print(random.random() * 100)
print(random.choice(List))
import datetime
import time
print(time.time())
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
Python sys module
The python sys module provides functions and variables which are used to manipulate
different parts of the Python Runtime Environment. It lets us access system-specific
parameters and functions.
import sys
First, we have to import the sys module in our program before running any functions.
sys.modules
69.1M
1.2K
This function provides the name of the existing python modules which have been
imported.
sys.argv
This function returns a list of command line arguments passed to a Python script. The
name of the script is always the item at index 0, and the rest of the arguments are stored
at subsequent indices.
sys.base_exec_prefix
This function provides an efficient way to the same value as exec_prefix. If not running a
virtual environment, the value will remain the same.
sys.base_prefix
It is set up during Python startup, before site.py is run, to the same value as prefix.
sys.byteorder
sys.maxsize
This function returns the largest integer of a variable.
sys.path
This function shows the PYTHONPATH set in the current system. It is an environment
variable that is a search path for all the python modules.
sys.stdin
It is an object that contains the original values of stdin at the start of the program and
used during finalization. It can restore the files.
sys.getrefcount
sys.exit
This function is used to exit from either the Python console or command prompt, and also
used to exit from the program in case of an exception.
sys executable
The value of this function is the absolute path to a Python interpreter. It is useful for
knowing where python is installed on someone else machine.
sys.platform
This value of this function is used to identify the platform on which we are working.
import sys
# importing sys.path
print(sys.path)
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’,
‘/usr/lib/python3.8/lib-dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-
packages’, ‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-
packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’,
‘/home/nikhil/.ipython’]
The sys module in Python provides various functions and variables that are
used to manipulate different parts of the Python runtime environment. It allows
operating on the interpreter as it provides access to the variables and functions
that interact strongly with the interpreter. Let’s consider the below example.
Example:
• Python3
import sys
print(sys.version)
Output:
• stdin
• stdout
• stderr
stdin: It can be used to get input from the command line directly. It is used for
standard input. It internally calls the input() method. It, also, automatically adds
‘\n’ after each sentence.
Example:
• Python3
import sys
print("Exit")
Output:
stdout: A built-in file object that is analogous to the interpreter’s standard output
stream in Python. stdout is used to display output directly to the screen console.
Output can be of any form, it can be output from a print statement, an expression
statement, and even a prompt direct for input. By default, streams are in text
mode. In fact, wherever a print function is called within the code, it is first written
to sys.stdout and then finally on to the screen.
Example:
import sys
sys.stdout.write('Geeks')
Output
Geeks
Example:
import sys
def print_to_stderr(*a):
print_to_stderr("Hello World")
Output:
Command Line Arguments
Command-line arguments are those which are passed during the calling of the
program along with the calling statement. To achieve this using the sys module,
the sys module provides a variable called sys.argv. It’s main purpose are:
• It is a list of command-line arguments.
• len(sys.argv) provides the number of command-line arguments.
• sys.argv[0] is the name of the current Python script.
Example: Consider a program for adding numbers and the numbers are passed
along with the calling statement.
# Python program to demonstrate
# command line arguments
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
# Addition of numbers
Sum = 0
print("\n\nResult:", Sum)
Output:
Exiting the Program
sys.exit([arg]) can be used to exit the program. The optional argument arg can
be an integer giving the exit or another type of object. If it is an integer, zero is
considered “successful termination”.
Note: A string can also be passed to the sys.exit() method.
Example:
# Python program to demonstrate
# sys.exit()
import sys
age = 17
if age < 18:
# exits the program
sys.exit("Age less than 18")
else:
print("Age is not less than 18")
Output:
An exception has occurred, use %tb to see the full traceback.
Output:
Output:
ModuleNotFoundError: No module named 'pandas'
sys.modules return the name of the Python modules that the current shell has
imported.
Example:
import sys
print(sys.modules)
Output:
Reference Count
sys.getrefcount() method is used to get the reference count for any given object.
This value is used by Python as when this value becomes 0, the memory for that
particular value is deleted.
Example:
• Python3
import sys
a = 'Geeks'
print(sys.getrefcount(a))
Output
4
What is epoch?
The epoch is the point where the time starts and is platform-dependent. On
Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC),
and leap seconds are not counted towards the time in seconds since the epoch.
To check what the epoch is on a given platform we can use time.gmtime(0).
Example: Getting epoch
• Python3
import time
print(time.gmtime(0))
Output:
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0,
tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
From the above example, you can see that epoch is 1 January 1970. This means
that 2 January 1970 can be expressed as 86400 seconds since epoch as there
are 86400 seconds in a day.
Note: The time before the epoch can still be represented in seconds but it will be
negative. For example, 31 December 1969 will be represented as -86400
seconds.
Getting current time in seconds since epoch
time.time() methods return the current time in seconds since epoch. It returns a
floating-point number.
Example: Current time in seconds since epoch
• Python3
import time
curr = time.time()
print("Current time in seconds since epoch =", curr)
Output
Current time in seconds since epoch = 1627908387.764925
import time
Output
Current time: Mon Aug 2 12:45:13 2021
import time
for i in range(4):
Output
0
1
2
3
time.struct_time Class
Struct_time class helps to access local time i.e. non-epochal timestamps. It
returns a named tuple whose value can be accessed by both index and attribute
name. Its object contains the following attributes –
1 tm_mon 1, 2, …, 11, 12
2 tm_mday 1, 2, …, 30, 31
3 tm_hour 0, 1, …, 22, 23
4 tm_min 0, 1, …, 58, 59
5 tm_sec 0, 1, …, 60, 61
6 tm_wday 0, 1, …, 6; Sunday is 6
8 tm_isdst 0, 1 or -1
This class contains various functions. Let’s discuss each function in detail.
time.localtime() method
localtime() method returns the struct_time object in local time. It takes the number
of seconds passed since epoch as an argument. If the seconds parameter is not
given then the current time returned by time.time() method is used.
Example: Getting local time from epoch
• Python3
print(obj)
Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=16,
tm_min=15, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)
time.mktime() method
time.mktime() is the inverse function of time.localtime() which converts the time
expressed in seconds since the epoch to a time.struct_time object in local time.
Example: Converting the struct_time object to seconds since epoch
• Python3
obj1 = time.gmtime(1627987508.6496193)
Output
Local time (in seconds): 1627987508.0
time.gmtime() method
time.gmtime() is used to convert a time expressed in seconds since the epoch to
a time.struct_time object in UTC in which tm_isdst attribute is always 0. If the
seconds parameter is not given then the current time returned by time.time()
method is used.
Example: Use of time.gmtime() method
• Python3
# importing time module
import time
Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10,
tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)
time.strftime() method
time.strftime() function converts a tuple or struct_time representing a time as
returned by gmtime() or localtime() to a string as specified by the format
argument. If t is not provided, the current time as returned by localtime() is
used. The format must be a string. ValueError is raised if any field in t is outside
of the allowed range.
Example: Converting struct_time object to a string using strftime() method
• Python3
Output
Tue, 03 Aug 2021 10:45:08
time.asctime() method
time.asctime() method is used to convert a tuple or a time.struct_time object
representing a time as returned by time.gmtime() or time.localtime() method to
a string of the following form:
Day Mon Date Hour:Min:Sec Year
Example: Converting tuple to time.struct_time object to string
• Python3
# importing time module
import time
obj = time.gmtime(1627987508.6496193)
obj = time.localtime(1627987508.6496193)
Output
Tue Aug 3 10:45:08 2021
Tue Aug 3 10:45:08 2021
time.strptime() method
time.strptime() method converts the string representing time to the struct_time
object.
Example: Converting string to struct_time object.
• Python3
import time
print(obj)
Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10,
tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=-1)
dir() is a powerful inbuilt function in Python3, which returns list of the attributes
and methods of any object (say functions , modules, strings, lists, dictionaries
etc.)
Syntax :
dir({object})
Parameters :
Returns :
dir() tries to return a valid list of attributes of the object it is called upon. Also,
dir() function behaves rather differently with different type of objects, as it aims
to produce the most relevant one, rather than the complete information.
• For Class Objects, it returns a list of names of all the valid attributes
and base attributes as well.
• Python3
Output :
Code #2 :
• Python3
• Python3
Output :
• Python3
Output :
Applications :
• The dir() has it’s own set of uses. It is usually used for debugging
purposes in simple day to day programs, and even in large projects
taken up by a team of developers. The capability of dir() to list out all
the attributes of the parameter passed, is really useful when handling
a lot of classes and functions, separately.
• The dir() function can also list out all the available attributes for a
module/list/dictionary. So, it also gives us information on the
operations we can perform with the available list or module, which can
be very useful when having little to no information about the module. It
also helps to know new modules faster.