0% found this document useful (0 votes)
3 views24 pages

Python Unit - III

Uploaded by

Aathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views24 pages

Python Unit - III

Uploaded by

Aathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Python: Unit - III

UNIT - III
Functions:
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high degree of
code reusing.
Python gives you many built-in functions like print(), etc. but you can also create your
own functions. These functions are called user-defined functions.

Defining a Function
Define functions to provide the required functionality. Here are simple rules to define
a function in Python.
 Function blocks begin with the keyword def followed by the function name and
parentheses ( ) .
 Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
 The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax:
def functionname( parameters ):
function_statements
return [expression]
Example:
def printme( str ):
#This prints a passed string into this function
print (str)
return

Calling a Function

Department of CS&IT, S.S.D.M College. 1


Python: Unit - III

Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
from another function or directly from the Python prompt.

Example:
# Function definition is here
def printme( str ):
#This prints a passed string into this function
print (str)
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Pass by reference vs value


All parameters (arguments) in the Python language are passed by reference. It means
if you change what a parameter refers to within a function, the change also reflects back in
the calling function.
Example:
def changeme( mylist ):
#This changes a passed list into this function
mylist.append([1,2,3,4]);
print ("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)
maintaining reference of the passed object and appending values in the same object.
where argument is being passed by reference and the reference is being overwritten
inside the called function.
Example:
def changeme( mylist ):

Department of CS&IT, S.S.D.M College. 2


Python: Unit - III

"This changes a passed list into this function"


mylist = [1,2,3,4]; # This would assign new reference in mylist
print ("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)

The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist.

Function Arguments
Call a function by using the following types of formal arguments −
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

Required arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error.
Example:
def printme( str ):
print str
return;
printme() #This will Gives Syntax Error

Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.

Department of CS&IT, S.S.D.M College. 3


Python: Unit - III

This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters. You can
also make keyword calls to the printme() function
Example:
def printme( str ):
print (str)
return;
printme( str = "My string")
def printinfo( name, age ):
print ("Name: ", name)
print ("Age ", age)
return;
printinfo( age=50, name="miki" )

Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.
Example:
def printinfo( name, age = 35 ):
print ("Name: ", name)
print ("Age ", age)
return;
printinfo( age=50, name="miki" )
printinfo( name="miki" ) #Returns age as 35

Variable-length arguments
Process a function for more arguments than you specified while defining the function.
These arguments are called variable-length arguments and are not named in the function
definition, unlike required and default arguments.
Syntax:
def functionname([formal_args,] *var_args_tuple):
function statements
return [expression]

Department of CS&IT, S.S.D.M College. 4


Python: Unit - III

An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments are
specified during the function call.
Example:
def printinfo( arg1, *vartuple ):
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return;
printinfo( 10 )
printinfo( 70, 60, 50 )

The Anonymous Functions


These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
 Lambda forms can take any number of arguments but return just one value in the form
of an expression. They cannot contain commands or multiple expressions.
 An anonymous function cannot be a direct call to print because lambda requires an
expression
 Lambda functions have their own local namespace and cannot access variables other
than those in their parameter list and those in the global namespace.
 Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function
stack allocation during invocation for performance reasons.
Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example:
sum = lambda arg1, arg2: arg1 + arg2;

print ("Value of total : ", sum( 10, 20 ) )


print ("Value of total : ", sum( 20, 20 ) )

Department of CS&IT, S.S.D.M College. 5


Python: Unit - III

The return Statement


The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return None.
Example:
def sum( arg1, arg2 ):
total = arg1 + arg2
print ("Inside the function : ", total)
return total;
total = sum( 10, 20 );
print ("Outside the function : ", total)

Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python.
 Global variables
 Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they
are declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total;
sum( 10, 20 );

Department of CS&IT, S.S.D.M College. 6


Python: Unit - III

print ("Outside the function global total : ", total)

Type Conversion
Type conversion, also known as type casting, refers to the process of converting a
value from one data type to another. This process is necessary when you want to perform
operations or manipulations that involve different types of data.
 Implicit Conversion
 Explicit Conversion

Implicit Conversion
Implicit type conversion, also known as automatic type conversion, occurs when the
programming language automatically converts data from one type to another without
requiring explicit instructions from the programmer. This process typically happens when
performing operations involving operands of different types.
Example:
num_int = 10
num_float = 3.5
result = num_int + num_float # Implicit conversion: num_int is
converted to float
print(result) # Output: 13.5

Explicit Conversion
Explicit type conversion, also known as manual type conversion or casting, involves
the programmer explicitly specifying the conversion from one type to another using
language-provided functions or syntax.
Example:
num_str = "123"
num_int = int(num_str) # Explicit conversion: string "123" is
converted to integer
print(num_int) # Output: 123

Common Conversions
Type conversion is commonly used in various scenarios:

Department of CS&IT, S.S.D.M College. 7


Python: Unit - III

Numeric Conversion:
 Convert from float to integer.
 Convert from integer to float.
String Conversion:
 Convert from integer/float to string.
 Convert from string to integer/float.
Boolean Conversion:
 Convert from integer/float/string to boolean.
 Convert from boolean to integer/float/string.

Handling Errors
Type conversion can sometimes lead to errors, especially when converting between
incompatible types or when converting to a type that cannot represent the original value.
Example:
try:
num = int("abc") # Raises ValueError: invalid literal for int() with
base 10
except ValueError:
print("Conversion failed: Invalid input")

Advantages:
 Flexibility: Type conversion enhances the flexibility of programming languages by
allowing operations between different data types. This flexibility enables developers
to write more versatile and expressive code.
 Simplicity: Type conversion simplifies code by reducing the need for explicit type
conversions. By automatically handling conversions when necessary, it makes code
more concise and readable.
 Compatibility: Type conversion promotes compatibility between different parts of a
program or between libraries and frameworks. It allows functions and modules to
accept a wider range of input data types, improving interoperability.

Department of CS&IT, S.S.D.M College. 8


Python: Unit - III

 Efficiency: In some cases, type conversion can improve code efficiency by allowing
operations to be performed directly on data of different types, without the need for
intermediate steps or data restructuring.

Disadvantages:
 Loss of Precision: Type conversion can lead to loss of precision or information,
especially when converting between numeric data types. For example, converting
from a floating-point number to an integer truncates the decimal part, potentially
leading to loss of accuracy.
 Unexpected Behavior: Type conversion may sometimes result in unexpected
behavior if not used carefully. Implicit conversions, in particular, can lead to subtle
bugs or errors if the programmer is not aware of the coercion rules defined by the
language.
 Debugging Complexity: Issues related to type conversion can be challenging to
debug due to their implicit nature. Tracking down errors resulting from incorrect or
unintended conversions may require careful examination of code execution flow.
 Performance Overhead: In performance-critical applications, frequent type
conversions may introduce a performance overhead. Converting data between
different types repeatedly can impact the overall execution speed of the program.
 Potential Errors: Type conversion can sometimes lead to errors, especially when
converting between incompatible types or when converting to a type that cannot
represent the original value. Proper error handling mechanisms, such as exception
handling, are essential to handle errors that may occur during type conversion.

Type Coercion
Type coercion, also known as implicit type conversion, is a fundamental concept in
programming languages where the language automatically converts one data type to another
during operations or assignments. This automatic conversion enables operations between
different data types without requiring explicit conversion by the programmer.
Type coercion serves as a mechanism for enabling operations between values of
different types without requiring explicit conversions by the programmer. Its primary
purposes include:

Department of CS&IT, S.S.D.M College. 9


Python: Unit - III

 Facilitating Operations: Type coercion allows for seamless interactions between


data of different types, enabling arithmetic operations, comparisons, and other
manipulations.
 Simplifying Code: By automatically handling type conversions, coercion reduces the
need for manual conversions, making code more concise and readable.
 Enhancing Flexibility: Programming languages with type coercion are more flexible,
as they allow developers to write code that can operate on a wider range of data types,
enhancing the language's versatility.
Example:
let result = 10 + "20"; // Result will be "1020" (implicit coercion of number
10 to string)
console.log(10 == "10"); // Result will be true (implicit coercion of string "10"
to number 10)
console.log(10 > true); // Result will be true (implicit coercion of boolean true
to number 1)

Conversion vs Coercion

Conversion Coercion
Explicit process of changing a value Implicit process of automatically converting a
from one type to another, typically value from one type to another, typically
performed by the programmer using performed by the language during operations or
language-provided functions or syntax. assignments.
Can be either explicit or implicit. Primarily implicit, though explicit conversions
are also possible.
Allows the programmer to change the Enables operations between values of different
data type of a value as needed for types without requiring explicit conversions,
specific operations or requirements. simplifying code and enhancing flexibility.
Requires explicit instructions from the May occur without explicit instructions, based
programmer, providing full control on predefined rules and language behavior,
over the conversion process. reducing direct control by the programmer.
Involves language-provided functions Coercion occurs automatically, without the
or syntax for converting values need for explicit syntax or instructions in most
between different data types. cases.
Converting a string to an integer using Adding an integer and a string, where the
the int() function. <br> - Converting a integer is coerced to a string for concatenation.

Department of CS&IT, S.S.D.M College. 10


Python: Unit - III

float to a string using the str() function. <br> - Comparing a number and a string, where
the string is coerced to a number for
comparison.
Errors are explicitly handled by the Errors may occur due to unexpected or
programmer, allowing for custom unintended coercion, potentially leading to
error messages or error handling logic. unexpected behavior or bugs in the code.
Generally improves code readability May reduce code readability, especially for
by making the conversion process developers who are not familiar with the
explicit and transparent. language's coercion rules, as it relies on
implicit conversions that may not be
immediately obvious.

Passing Functions to a Function


Passing functions as arguments to other functions, also known as higher-order
functions, is a powerful feature in many programming languages. It allows for dynamic
behavior and enables functions to be used as data. This means that functions can be passed as
arguments to other functions, returned from functions, and assigned to variables.

Definition
Passing functions to a function involves providing a function as an argument when
calling another function. This allows the receiving function to execute the passed function
within its own execution context.
Example:
def function1(arg1, arg2, func):
# Function1 code
result = func(arg1, arg2) # Call the passed function with arguments
# More code
return result

def function2(x, y):


return x + y

# Pass function2 as an argument to function1


result = function1(3, 4, function2)
print(result) # Output: 7

Department of CS&IT, S.S.D.M College. 11


Python: Unit - III

In this example:
 function1 is a function that takes three arguments: arg1, arg2, and func.
 Inside function1, func is called with arg1 and arg2.
 function2 is defined separately and passed as an argument to function1.
 When function1 is called with 3, 4, and function2, it executes function2(3, 4)
and returns the result.

Advantages:
 Modularity and Reusability: Passing functions as arguments promotes modularity
by allowing functions to be defined independently and reused in different contexts.
This enhances code reusability, as functions can be easily applied to multiple
scenarios without modification.
 Dynamic Behavior: It enables dynamic behavior in programs by allowing functions
to be parameterized with different behaviors. This flexibility allows algorithms to
adapt to different use cases or requirements dynamically, enhancing the versatility of
the code.
 Abstraction and Encapsulation: Functions passed as arguments can encapsulate
complex behavior, abstracting away implementation details and promoting a higher
level of abstraction. This enhances code readability and maintainability by focusing
on the intent of the code rather than low-level details.
 Expressiveness and Conciseness: Using higher-order functions leads to more
expressive and concise code. It allows complex operations to be expressed in a
compact and elegant manner, leading to cleaner and more readable code.
 Functional Programming Paradigm: Passing functions to other functions is a core
concept in functional programming, enabling the use of higher-order functions,
function composition, and other functional programming techniques. Functional
programming promotes immutability, declarative programming, and side-effect-free
functions, leading to more predictable and maintainable code.

Disadvantages:
 Complexity and Indirection: While passing functions as arguments increases
flexibility, it can also introduce complexity and indirection, making the code harder to

Department of CS&IT, S.S.D.M College. 12


Python: Unit - III

understand for developers who are not familiar with functional programming concepts.
Overuse of higher-order functions may lead to code that is difficult to reason about.
 Performance Overhead: In some cases, passing functions as arguments may
introduce a performance overhead, especially in languages where function calls are
expensive. This overhead may be negligible in most cases but can become significant
in performance-critical applications or hotspots.
 Debugging and Error Handling: Debugging code that heavily relies on passing
functions to other functions can be challenging, especially when dealing with complex
control flows or higher-order functions. Errors may occur due to incorrect usage of
function arguments or unexpected behavior of callback functions.
 Readability: While higher-order functions can lead to more expressive code, they
may also reduce code readability for developers who are not familiar with functional
programming paradigms. Functions passed as arguments may be defined elsewhere in
the codebase, leading to difficulties in understanding the flow of execution.
 Potential for Abstraction Leakage: In some cases, passing functions as arguments
may lead to abstraction leakage, where implementation details of the passed function
are exposed to the calling code. This violates the principle of encapsulation and may
lead to tighter coupling between components.

Mapping Functions
A mapping function typically refers to a function that applies a specified operation to
each element in a sequence (e.g., a list, tuple, or dictionary) and returns a new sequence
containing the results. This operation could be anything from applying a mathematical
function to transforming the elements in some way.

Mapping Functions in Python:


Applying a Function to Each Element:
 A mapping function applies a specified function to each item in an iterable (e.g., a list,
tuple, or dictionary) and returns an iterable that contains the results.
 The function applied to each element can be a built-in function, a user-defined
function, or a lambda function.

Department of CS&IT, S.S.D.M College. 13


Python: Unit - III

Transforming Data:
 Mapping functions are commonly used to transform data by applying a transformation
or operation to each element in a sequence.
 This transformation can involve mathematical operations, string manipulation, data
type conversions, or any other operation that modifies the elements.

Mapping functions in a dictionary involves associating function names or keys with


their corresponding function objects as values in a Python dictionary. This allows for easy
access and dispatching of functions based on keys or names.
Example:
# Define functions for different operations
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
# Create a dictionary mapping operation names to functions
operation_dict = {
'add': add,
'subtract': subtract,
'multiply': multiply,
'divide': divide
}
# Example usage: performing an operation based on a key
operation_name = 'add'
result = operation_dict[operation_name](4, 2) # Calling the 'add'
function with arguments 4 and 2
print("Result of {} operation:".format(operation_name), result) #
Output: 6

Department of CS&IT, S.S.D.M College. 14


Python: Unit - III

In this example:
 Four functions (add, subtract, multiply, divide) are defined to perform
different arithmetic operations.
 A dictionary operation_dict is created where operation names ('add', 'subtract',
etc.) are mapped to their corresponding function objects.
 You can access and call a function from the dictionary using its key. For
example, operation_dict['add'] returns the add function, which can then be
called with arguments as usual.
 This approach allows for dynamic selection and execution of functions based
on keys or names, which can be useful in scenarios where different functions
need to be called based on runtime conditions or user input.

Modules
A module allows you to logically organize your Python code. Grouping related code
into a module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
def greeting(name):
print("Hello, " + name)
Save the code as file in any name with .py extension to create the module. Just save
this code as myModule.py.

The import Statement


Use any Python source file as a module by executing an import statement in some
other Python source file.
Syntax:
import module1[, module2[,... moduleN]
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 before importing a module.
import myModule
myModule.greeting("Jonathan")

Department of CS&IT, S.S.D.M College. 15


Python: Unit - III

Variables in Module
The module can contain functions, like that variable of all types (arrays, dictionaries,
objects etc) also can be written inside the file to create module.
#myModule.py
person = {
"name": "John",
"age": 36,
"country": "Norway"
}
#mainFile.py
import myModule
a = myModule.person["name"]
print (a)

The from...import Statement


Pythons from statement lets you import specific attributes from a module into the
current namespace.
Syntax:
from modname import name1[, name2[, ... nameN]]
Example:
#myModule.py
def greeting(name):
print("Hello, " + name)
person = {
"name": "John",
"age": 36,
"country": "Norway"
}

#mainFile.py
from myModule import person
print (person["age"])

Department of CS&IT, S.S.D.M College. 16


Python: Unit - III

Naming and Re-Naming a Module


Naming a module file is just give any file name with .py extension, the extension is
must.
Renaming a module, which means creating an alias name when you import the
module by using the as keyword.
#mainFile.py
import myModule as myMod
a = myMod.person["name"]
print (a)

Standard Modules
There are several built-in modules in Python, which you can import whenever you
like.

sys module
The sys module in Python provides access to system-specific parameters and
functions. It is part of Python's standard library, meaning it comes pre-installed with Python
and does not require any additional installation.

Functions and Attributes


 sys.argv: This attribute provides a list of command-line arguments passed to a Python
script. The first item (sys.argv[0]) is the script name itself.
 sys.exit([arg]): This function exits the Python interpreter by raising the SystemExit
exception. It can optionally take an integer argument arg as the exit status (default is
0).
 sys.path: This attribute provides a list of directories where Python looks for modules
when importing. You can manipulate this list to add custom directories or modify the
import behavior.
 sys.platform: This attribute contains a string identifying the operating system platform.
It can be used to write platform-independent code.
 sys.version: This attribute contains a string representing the Python version and
additional build information.

Department of CS&IT, S.S.D.M College. 17


Python: Unit - III

 sys.stdin, sys.stdout, sys.stderr: These attributes represent the standard input, output,
and error streams, respectively.
Example:
import sys

# Print command-line arguments


print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])

# Exit the script with a custom exit status


sys.exit(1)

# Print Python version and platform


print("Python version:", sys.version)
print("Platform:", sys.platform)

# Manipulate sys.path to add a custom directory


sys.path.append("/path/to/custom/module")

# Redirect stdout to a file


with open("output.txt", "w") as f:
sys.stdout = f
print("Hello, world!")
sys.stdout = sys.__stdout__ # Restore stdout

math module
The math module in Python provides access to mathematical functions and constants,
allowing you to perform mathematical operations beyond the basic arithmetic operations
provided by the core Python language.

Functions and Constants

Department of CS&IT, S.S.D.M College. 18


Python: Unit - III

 Mathematical Functions: The math module provides various mathematical functions


such as trigonometric functions (sin(), cos(), tan()), exponential and logarithmic
functions (exp(), log()), and more.
 Constants: It also includes mathematical constants such as π (pi) and e (Euler's
number) as attributes: math.pi and math.e.
Example:
import math

# Calculate the square root of a number


print("Square root of 25:", math.sqrt(25)) # Output: 5.0

# Calculate the value of pi


print("Value of pi:", math.pi) # Output: 3.141592653589793

# Calculate the sine of an angle in radians


print("Sine of pi/2:", math.sin(math.pi / 2)) # Output: 1.0

# Calculate the natural logarithm of a number


print("Natural logarithm of 10:", math.log(10)) # Output:
2.302585092994046

# Calculate the factorial of a number


print("Factorial of 5:", math.factorial(5)) # Output: 120

Use Cases
 Scientific and Engineering Applications: The math module is commonly used in
scientific and engineering applications where precise mathematical calculations are
required.
 Geometry and Trigonometry: It is useful for calculating geometric properties, angles,
distances, and trigonometric functions.
 Financial Calculations: It can be used for financial calculations, such as compound
interest or present value calculations.

Department of CS&IT, S.S.D.M College. 19


Python: Unit - III

 Statistical Analysis: While Python's statistics module provides statistical functions,


the math module complements it with additional mathematical operations.
The math module is a powerful tool for performing mathematical calculations in Python,
providing a wide range of functions and constants for various mathematical needs. It is a
standard library module, so it is available in any Python environment without the need for
additional installation.
time module
The time module in Python provides various functions for working with time-related
tasks, including measuring time, formatting time, and manipulating timestamps. It is a part of
Python's standard library, meaning it comes pre-installed with Python and does not require
any additional installation.

Some Functions and Constants:


 time(): Returns the current time in seconds since the epoch (January 1, 1970, 00:00:00
UTC).
 sleep(seconds): Suspends the execution of the current thread for the given number of
seconds.
 ctime(timestamp): Converts a timestamp (number of seconds since the epoch) to a
string representing the local time.
 gmtime(timestamp): Converts a timestamp to a time.struct_time object representing
the UTC time.
 strftime(format, t): Converts a time.struct_time object or timestamp to a string
representation based on the specified format.
 strptime(string, format): Parses a string representing a time according to the given
format and returns a time.struct_time object.
Example:
import time

# Get the current time in seconds since the epoch


current_time = time.time()
print("Current time:", current_time)

# Sleep for 2 seconds

Department of CS&IT, S.S.D.M College. 20


Python: Unit - III

print("Sleeping for 2 seconds...")


time.sleep(2)
print("Woke up!")

# Convert a timestamp to a string representing local time


local_time_string = time.ctime(current_time)
print("Local time:", local_time_string)

# Convert a timestamp to a UTC time struct


utc_time_struct = time.gmtime(current_time)
print("UTC time struct:", utc_time_struct)

# Format a time struct as a string


formatted_time = time.strftime("%Y-%m-%d %H:%M:%S",
utc_time_struct)
print("Formatted time:", formatted_time)

# Parse a string representing time


parsed_time = time.strptime("2023-12-25", "%Y-%m-%d")
print("Parsed time struct:", parsed_time)

Use Cases
 Delaying Execution: time.sleep() can be used to introduce delays or wait periods in
scripts or programs.
 Measuring Time: time.time() is commonly used for measuring execution time or
benchmarking.
 Formatting Time: time.strftime() allows for custom formatting of time strings, useful
for logging, displaying timestamps, or generating file names.
 Converting Time Zones: time.gmtime() and time.localtime() are used for converting
timestamps between UTC and local time zones.

The dir( ) Function

Department of CS&IT, S.S.D.M College. 21


Python: Unit - III

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.
import platform
x = dir(platform)
print(x)
help Function
The help() function in Python is a built-in function that provides interactive help for
objects, modules, functions, classes, methods, keywords, and other Python entities. It displays
documentation strings (docstrings) associated with these objects, which describe their
purpose, usage, parameters, and return values.
Syntax:
help([object])
object (optional): The object for which you want to retrieve help information. If no
object is provided, it starts an interactive help session.
Example:
help(abs)

Plotting
Plotting refers to the process of creating graphical representations of data using charts,
graphs, or plots. Python provides several libraries for data visualization, such as Matplotlib,
Seaborn, Plotly, and Pandas, which offer a wide range of plotting capabilities. These libraries
provide functions and classes to create various types of plots, including line plots, bar plots,
scatter plots, histograms, pie charts, and more. Plots are useful for visualizing data patterns,
relationships, and trends, making them a powerful tool for data analysis, reporting, and
presentation.

Matplotlib
Matplotlib is a popular data visualization library for Python. It provides a wide range
of tools to create different types of plots and graphs, including line plots, scatter plots, bar
plots, histograms, and many others. Matplotlib allows users to create publication-quality
figures with just a few lines of code.

Department of CS&IT, S.S.D.M College. 22


Python: Unit - III

Matplotlib is highly customizable and provides a variety of options to adjust the


appearance of the plots, such as changing the color, line style, marker style, adding titles and
labels, setting axis limits, and many more. It can also be used with other libraries like NumPy
and Pandas to work with large datasets.
Some popular modules in Matplotlib are pyplot, which provides a MATLAB-like
interface to create plots, and axes, which allows for more fine-grained control over the plot.
Matplotlib also provides different styles to change the appearance of the plots, and the ability
to save the plots in different file formats like PNG, PDF, and SVG.
Example:
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a figure and axis
fig, ax = plt.subplots()
# Plot the data
ax.plot(x, y)
# Set labels and title
ax.set_xlabel('X-axis label')
ax.set_ylabel('Y-axis label')
ax.set_title('Line Plot')
# Show the plot
plt.show()
The above code will create a line plot with the given data and display it using the
plt.show() function.

Department of CS&IT, S.S.D.M College. 23


Python: Unit - III

Department of CS&IT, S.S.D.M College. 24

You might also like