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

Python Notes - Unit - 2

Uploaded by

Titus Martin
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 views18 pages

Python Notes - Unit - 2

Uploaded by

Titus Martin
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

UNIT-2

Python Functions
In python, function is a block of code, and it will contain a series of statements to execute
whenever it is called in the program.
Functions are self-contained programs that perform some particular tasks. Once a function is
created by the programmer for a specific task, this function can be called anytime to perform that
task.
Suppose, we want to perform a task several times, in such a scenario, rather than writing code
for that particular task repeatedly, we create a function for that task and call it when we want to
perform the task. Each function is given a name, using which we call it. A function may or may
not retum a value.
There are many built-in functions provided by Python such as dir ( ) , len ( ) , abs ( ) , etc. Users
can also build their own functions, which are called user-defined functions. There are many
advantages of using functions:
a) They reduce duplication of code in a program.
b) They break the large complex problems into small parts.
c) They help in improving the clarity of code (i.e., make the code easy to understand).
d) A piece of code can be reused as many times as we want with the help of functions
Defining a Function
To define a function in python, you need to use the def keyword followed by the function name
and parentheses ( ). Following is the syntax of defining the function in python.
Function Syntax

In the above function syntax, we used different components to define the function.
1. The def keyword is used to indicate the start of the function.
2. function_name is the name to uniquely identify the function.
3. parameters are optional and these are useful to send values to the function.
4. The colon (:) symbol is used to indicate the start of the code block.
5. statement(s) inside the function body to perform the required tasks, and the statements must
follow the same indentation.
6. The return statement is useful to return a value from the function, and it’s optional.
To create a block of statements inside of the function body, you need to follow the same
indentation for all the statements.
def Statements
The def statement creates a function object and assigns it to a name. Its general format
is as follows:
def <name>(arg1, arg2,... argN):
<statements>
As with all compound Python statements, def consists of a header line followed by a block of
statements, usually indented (or a simple statement after the colon). The statement block
becomes the function’s body—that is, the code Python executes each time the function is called.
The def header line specifies a function name that is assigned the function object, along

1
with a list of zero or more arguments (sometimes called parameters) in parentheses. The
argument names in the header are assigned to the objects passed in parentheses at the point of
call.
Function bodies often contain a return statement:
def <name>(arg1, arg2,... argN):
...
return <value>
The Python return statement can show up anywhere in a function body; it ends the function call
and sends a result back to the caller. The return statement consists of an object expression that
gives the function’s result. The return statement is optional; if it’s not present, the function exits
when the control flow falls off the end of the function body. Technically, a function without a
return statement returns the None object automatically, but this return value is usually ignored.
Functions may also contain yield statements, which are designed to produce a series of values
over time
Types of Functions in Python
Below are the different types of functions in Python:
1. Built-in library function: These are Standard functions in Python that are available to
use.
2. User-defined function: We can create our own functions based on our requirements.

BUILT-IN FUNCTIONS
Built-in functions are the functions already defined in the Python programming language; we
can directly call them to perform a specific task. Every built-in function in Python performs
some particular task. For example, the Math module has some mathematical built-in functions
that perform tasks related to mathematics.
Some built-in functions provided in the Python programming language.
1. print() – Display Output
print("Hello Students")
print(10 + 20)
2. input() – Take Input from User
name = input("Enter your name: ")
print("Welcome", name)
3. len() – Find Length
text = "Python"
print(len(text))
4. type() – Check Data Type
x = 10
y = 3.5
z = "Hello"
print(type(x))
print(type(y))
print(type(z))
5. max() – Find Maximum Value
numbers = [10, 25, 5, 40]
print(max(numbers))
6. min() – Find Minimum Value
numbers = [10, 25, 5, 40]
print(min(numbers))
7. sum() – Add All Values
numbers = [10, 20, 30]
print(sum(numbers))

2
8. abs() – Absolute Value
print(abs(-15))

USER DEFINED FUNCTIONS


Python also allows users to define their own functions. To use their own functions in
Python, users have to define the function first; this is known as Function Definition. In a
function definition, users have to define a name for the new function and also the list of the
statements that will execute when the function will be called.
Defining a Function:
The block of the function starts with a keyword def after which the function name is
written followed by parentheses. We can also give some input parameters or arguments to a
function by placing them within these parentheses. The parameters can also be defined within
these parentheses. The block of statements always starts with a colon (:). After writing the code
statements, the block is ended with a return statement whose syntax is return [expression]. As we
have stated earlier, a function may or may not return a value. If you want to return more than one
value, separate the values using commas. The default return value is NONE.
Syntax
def functionname (parameters):
"function docstring"
statement(s)
return[expression]
In any type of programming language, a docstring is a string literal which is used to
document a specific part of the code. It is used just like the comments in the programming
language. It does not affect the program execution but it is considered to be a good practice to
use docstrings.
Example
def greet(): # Function Definition
print("Hello! Welcome to Python.") # body of the function
greet() # Calling the function
The function definition is always preceded by the keyword de f. In the given example,
greet() is the name of the function.
The rules for defining a function name are same as those for variable names:
1. Alphabets, numerals and some special characters are allowed.
2. The name of the function cannot start with a number.
3. No keyword can be used as the name of the function.
4. Giving the same name to a variable and a function should be avoided.
5. The parentheses after the function name contain the parameters or arguments. They are
optional.
The first line in the definition of function is known as header and the rest is abbreviated as body.
The header line will always end with a colon. All the statements meant to execute at the time of
function calling are defined in the body part only. We can define any number of statements in
the body of the function definition.
Calling a Function:
……………. Def fun1()
……………. ………………
fun1() ……………….
……………. …………….…
……………. ……………….
In the above figure which explains how a function func1() is called to perform a well defined
task. As soon as func1() is called, the program control is passed to the first statement in the

3
function. All the statements in the function are executed and then the program control is passed
to the statement following the one that called the function.
def fun1() def fun2() def fun3() def fun4()
…………….. …………….. …………….. ……………..
……………. ……………. ……………. …………….
fun2() fun3() fun4() …………….
…………….. …………….. …………….. ……………..
……………. ……………. ……………. …………….
In the above figure, func1() calls function named func2(). Therefore, func1() is known as the
calling function and func2() is known as the called function. The moment the compiler
encounters a function call, instead of executing the next statement in the calling function, the
control jumps to the statements that are a part of the called function. After called function is
executed, the control is returned back to the calling program.
It is not necessary that the func1() can call only one function, it can call as many functions as it
wants and as many times as it wants. For example, a function call placed within for loop or while
loop may call the same function multiple times until the condition holds true.
Function without Parameters:
A function without arguments, doesn't take any values as input when it is called. Instead, it
performs some computation based on its internal logic and returns a result.
def add_numbers():
a = 5 # Assigning values inside the function
b = 10
return a + b # Returning the sum
result = add_numbers() # Calling function without arguments
print("Sum:", result)

Function with Parameters:


A function with arguments takes one or more values as input when it is called. These values are
specified inside the parentheses when you call the function, and they are passed to the function
as parameters. The function can then use these parameters to perform some computation and
return a result.
def add_numbers(a, b):
return a + b
result = add_numbers(5, 10)
print("Sum:", result)
The Return Statement
A return statement is used to end the execution of the function call and it “returns” the value of
the expression following the return keyword to the caller. The statements after the return
statements are not executed. If the return statement is without any expression, then the special
value None is returned. A return statement is overall used to invoke a function so that the passed
statements can be executed.
Recursion:
We know that in Python, a function can call other functions. It is even possible for the function
to call itself. These type of construct are termed as recursive functions.
It is always made up of 2 portions, the base case and the recursive case.
1. The base case is the condition to stop the recursion.
2. The recursive case is the part where the function calls on itself.
Example: Factorial using Recursion
def factorial(x):
if x == 1: # This is the base case

4
return 1
else: # This is the recursive case
return(x * factorial(x-1))
print(factorial(4))
Explanation:
Now let's analyse what is going on in the above recursive function.
First, when we pass the integer 4 into the function, it goes to the recursive case return
(x * factorial(x-1)) which will give us return(4 * factorial(3)).
Next, the function will call factorial(3) which will give us return(3 * factorial(2)) and it goes
on until we have x == 1 (the base case) and then the recursion will terminate. This means that if
we do not have a base case to stop the recursion, the function will continue to call itself
indefinitely. At the end we will have return(4 * 3 * 2 * 1)
Python Scope of Variables
In Python, variables are the containers for storing data values. Unlike other languages like
C/C++/JAVA, Python is not “statically typed”. We do not need to declare variables before using
them or declare their type. A variable is created the moment we first assign a value to it. The
location where we can find a variable and also access it if required is called the scope of a
variable.
Python Local variable
Local variables are those that are initialized within a function and are unique to that
function. It cannot be accessed outside of the function. Let’s look at how to make a local
variable.
Example:
def show():
x = 10 # local variable
print(x)
show()
# print(x) # ❌ error
Output:
Python Class

If we will try to use this local variable outside the function then let’s see what will happen.
Example:
def f():
# local variable
s = "Python Class"
print("Inside Function:", s)
f()
print(s)
Output:
name 's' is not defined

Python Global variables


Global variables are the ones that are defined and declared outside any function and are not
specified to any function. They can be used by any part of the program.
Example:
# This function uses global variable s
def f():
print(s)
# Global scope
s = "Python Class"
f()
5
Exceptions:
An exception in Python is an incident that happens while executing a program that causes the
regular course of the program's commands to be disrupted. When a Python code comes across a
condition it can't handle, it raises an exception. An object in Python that describes an error is
called an exception.
When a Python code throws an exception, it has two options: handle the exception immediately
or stop and quit.
While writing a program, we often make some errors. There are many types of errors that can
occur in a program. The error caused by writing an improper syntax is termed syntax error or
parsing error; these are also called compile time errors.
Errors can also occur at runtime. There are various types of runtime errors in Python. Let us look
at a few examples. When a file we try to open does not exist, we get a FileNotFoundError. When
a division by zero happens, we get a ZeroDivisionError. When the module we are trying to
import does not exist, we get an ImportError. Python creates an exception object for every
occurrence of these run-time errors. The user must write a piece of code that can handle the
error. If it is not capable of handling the error, the program prints a trace back to that error along
with the details of why the error has occurred.
There are two types of exceptions.
1. Built in Exceptions
2. User defined exceptions
Built in Exceptions (System defined exceptions):
System defined exceptions are predefined types of exceptions that are already defined by
the python system. These exceptions are also called built in exceptionsthat are available in
python standard library collection to deal with common errors that may occur during the
execution of program. Some commonly used built in exceptions in python are as follows;
1. Syntax errors:
This exception is raised when the interpreter finds a syntax error while executing the
program code. The syntax error generally occur in the program when we violate any
grammatical rules of the programming language. These are the most basic type of error.

Example:
print x
Output:
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
2. Indentation Error:
This exception is raised when indentation (such as inconsistent use of tabs and spaces) is not
specified properly. When we write a program, Python uses indentation to nested blocks. Each
line in a block must have the same indentation level. If this rule is broken, an IndentationError
occurs.
Example:
def func():
print("This function has incorrect indentation.")
print("This line should be properly indented.")
#Calling the function to trigger the error func()
Output:
IndentationError: expected an indented block after function definition on line 2.
3. NameError:
This type of exception occurs when an identifier or variable is not found in the local or global
namespace. In other words, if non-existent identifier used, NameError exception occurs. Look at
the example below on it.
Example:
def func():

6
variable = 10
print("The value of the variable is:", varible)
func()
Output:
NameError: name 'varible' is not defined. Did you mean: 'variable'?
4. TypeError:
This type of exception occurs when invalid data type is supplied to an operation or function. It
can be caused due to several possible reasons.
They are:
Attempting to access elements within a string, list, or tuple using something other than an
integer. For example, if we try to access elements of a list or characters of a string using a non-
integer value (like a string, float, or any non-numeric value) as an index, Python raises an error,
specifically a TypeError.
When we pass the wrong number of arguments to a function or method.
Mismatch between elements in a format string and element passed for conversion.
Example:
def div(a, b):
result = a/b # Attempting to divide two values
return result
#Calling the function with incompatible types.
result = div("10", 2) # Dividing a string by an integer
print("Result:", result)
Output:
TypeError: unsupported operand type(s) for /: 'str' and 'int'

5. ZeroDivisionError:
This type of exception occurs in a program when we attempt to divide a number by zero. Here's
an example code that raises a ZeroDivisionError:
Example:
def divide numbers(a, b):
result = a/b
return result
result = divide_numbers(8, 0)
print("Result:", result)

Output:
ZeroDivisionError: division by zero.

6. FileNotFoundError:
The FileNotFoundError exception occurs when we attempt to open or access a file that does not
exist.
The below is an example code that causes a FileNotFoundError.
Example:
f = open("nonexistent_file.txt", "r") # File does not exist
content = [Link]()
[Link]()

Output:
File not found. Error: [Errno 2] No such file or directory: 'nonexistent [Link]'.

7. IndexError:

7
The IndexError exception occurs when we try to access an element of a sequence (like a string,
list or tuple) using an invalid index number. Here's an example code that triggers an IndexError
without handling the exception:
Example:
numbers = [1, 2, 3]
result = numbers[4]
print("Result:", result)
Output:
IndexError: list index out of range
8. KeyError:
The KeyError exception occurs in a program when we try to access a dictionary key that does
not exist. Look at the below example. Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict['d']
print("Value:", value)

Output:
KeyError: 'd'

9. AttributeError:
The AttributeErrorexception occurs in the program when we attempt to access an attribute or
method that does not exist. If an AttributeError indicates that an object has NoneType, meaning
it is None. Look at the below example.
Example:
class Car:
def start(self):
print("Car started.")

c = Car()
[Link]()

Output:
AttributeError: 'Car' object has no attribute 'stop'

User defined Exceptions:


Try and Except Statement:
In Python, we catch exceptions and handle them using try and except code blocks. The “try”
clause contains the code that can raise an exception, while the “except” clause contains the code
lines that handle the exception.
Syntax of try-except Block:
try:
# Code that might cause an error
risky_operation()

except ExceptionType:
# Code to handle the error
handle_error()

1. The “try” block contains the code that may cause an error.
2. The “except” block catches the error and executes alternative code.
3. Exception Type is optional and can be used to handle specific types of errors.

8
Example 1 Handling Division by Zero:
try:
num1 = 10
num2 = 0
result = num1 / num2 # This will cause ZeroDivisionError

except ZeroDivisionError:
print("Error: Cannot divide by zero!")

print("Program continues...")

Example 2: Handling Multiple Exceptions


try:
num = int(input("Enter a number: "))
result = 10 / num

except ZeroDivisionError:
print("Error: You cannot divide by zero!")

except ValueError:
print("Error: Please enter a valid number!")

9
Python and OOP
Python is an object-oriented language since its beginning. It allows us to develop applications
using an Object-Oriented approach. In Python, we can easily create and use classes and objects.
An object-oriented paradigm is to design the program using classes and objects. The object is
related to real-word entities such as book, house, pencil, etc. The oops concept focuses on
writing the reusable code. It is a widespread technique to solve the problem by creating objects.
Basic Terms in OOP:
Class: Classes are defined by the user; the class provides the basic structure for an object. It
consists of data members and method members that are used by the instances (objects) of the
class.
Class Variable: A variable that is defined in the class and can be used by all the instances of
that class.
Data Member: A variable defined in either a class or an object; it holds the data associated with
the class or object.
Object: The object is an entity that has state and behavior. It may be any real-world object
like the mouse, keyboard, chair, table, pen, etc. Everything in Python is an object, and almost
everything has attributes and methods. Object is an instance of a class. When we define a class,
it needs to create an object to allocate the memory.
Method: Methods are the functions that are defined in the definition of class and are used by
various instances of the class.
Abstraction: It refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are defined as a
list of abstract attributes such as size, weight, cost and functions to operate on these attributes.
Inheritance: In python, inheritance is the main concept of Object-Oriented Programming
(OOP), and it is helpful to inherit all the properties and methods from one class to another class.
To implement the inheritance process in python, you need to define the child class with
parentheses ( ) by including the base class.
Polymorphism: Polymorphism means the ability to take more than one form. The process of
making an operator to exhibit different behaviours in different instances is known as operator
overloading.
Defining a Class:
A class can be defined as a blue print or a previously defined structure from which objects are
made. It can also be defined as a group of objects that share similar attributes and relationships
with each other.
For example:
1. Fruit is a class, and apple, mango and banana are its objects. The attributes of
these objects can be color, taste, etc.
2. Vehicle is a class and car, scooter, bus, truck, etc., can be its objects. The
attributes of these objects can be speed, brake, power of engine, etc.
In Python, a class is defined by using a keyword class. After that, the first statement can be a
docstring (optional) that contains the information about the class. Now, in the body of class, the
attributes are defined. These attributes can be data members or method members.
In Python, as soon as we define a class, the interpreter instantly creates an object that has the
same name as the class name. Although, we can create more objects of the same class. With the
help of objects, we can access the attributes defined in the class.
Syntax
class class name:
‘This is docstring which is optional'
class_suite
A new local new space is created by a Class, where all its attributes (data or function) are
defined. As soon as the class is defined, a new class object is created with same name, which
allows access to the different attributes, also to instantiate new object of that class.

10
The class has a documentation string which can be accesed via ClassName_doc_
The class_suite consists of all the component statements defining class members, data
attributes and functions.
Example:
class Dog:
sound = "bark"
# Create an object from the class
d = Dog()
# Access the class attribute
print([Link])

Inheritance:
Inheritance is a very important concept in OOP. It is used to inherit the properties and
behaviours of one class to another. The class that inherits another class is called a child and the
class that gets inherited is called a base class or parent class. It means the reusability of code. It
is the capability of a class to derive the properties of another class that has already been created.
Let us look at an example

1. Vehicle is a class that is further divided into two subclasses, automobiles (driven by
motors) and pulled vehicles (driven by men). Therefore, vehicle is the base class and
automobiles and pulled vehicles are its subclasses. These subclasses inherit some of the
properties of the base class vehicle.
2. Truck and car are the subclasses of the class automobile that is the base class for them.
They inherit some of the properties of base class automobiles. Similarly, the rickshaw and
bullock cart are the subclasses of pulled vehicles that serves as the base class for them.
The main advantage of inheritance in the context of programming is that the code can be
written once in the base class and then reused repeatedly in the subclasses.

Creating a Parent Class:


The class whose attributed and methods are inherited is called as parent class. It is defined just
like other classes ie.e., using the class keyword.
Syntax:
Class ParentClassName:
{class body}
Creating a Child Class:
Classes that inherit from base classes are declared similarly to the parent class, however, we
need to provide the name of parent classes with in the parenthesis.
Syntax:
Class SubclassName(ParenClass1[,ParentClass2,…]):
{sub class body)

Inheritance:

11
Inheritance is a fundamental concept in object oriented programming (OOP) that allows one
class (child or derived class) to acquire the properties and methods of another class (parent or
base class) or promotes code reusability and helps in building a hierarchical classification.
Types of Inheritance in Python:
Python supports various types of inheritance.
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hybrid Inheritance

Single Inheritance: One base class and one derived class are involved in single inheritance. The
characteristics and methods of the base class are passed down to the derived class. It enabling
code reusability and addition of new features to existing code.

B
Example Program:
Class Animal:
Single Inheritance
def speak(self):
print(“Animal Speaks”)

#Child Class
Class Dog(animal):
Def bark(self):
Print(“Dog barks”)

#creating an object of the Dog class


D=Dog()
[Link]() #inherited from Animal
[Link]() # Defined in Dog class

Multiple Inheritance: Multiple Inheritance entails more than one base class and one derived
class. All of the base classes characteristics and methods are passed down to the derived class. It
allows the derived class to aggregate and use functionality from several sources.

A B

C
Example:
Multiple Inheritance
12
class Calculation1:
def Summation(self,a,b):
return a+b;

class Calculation2:
def Multiplication(self,a,b):
return a*b;

class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;

d = Derived()
print([Link](10,20))
print([Link](10,20))
print([Link](10,20))

Multilevel Inheritance: A chain of inheritance with numerous levels is referred to as multilevel


inheritance. A derived class inherits from a base class, which in turn inherits from another
derived class. This results in a hierarchical structure in which each class inherits its parent
classes characteristics and methods.

B
Example: Multilevel Inheritance
class Animal:
def speak(self):
print("Animal Speaking") C
Single Inheritance
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")

#The child class Dogchild inherits another child class Dog


class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
[Link]()
[Link]()
[Link]()

Hybrid Inheritance: The term hybrid inheritance refers to the combination of multiple
inheritance and multilevel inheritance. It enables a customize class hierarchy with a mix of
features from several inheritance types. When a class needs to inherit from numerous base

13

Class A Class A
classes and participate in a multilayer inheritance chain, this type of inheritance is beneficial.

Example:
class A:
def method_a(self):
print('Method A')
class B(A):
def method_b(self):
print('Method B')
class C(A):
def method_c(self):
print('Method C')
class D(B,C):
def method_d(self):
print('Method D')
My_object=D()
My_object.method_a() # Output: Method A
My_object.method_b() # Output: Method B
My_object.method_c() # Output: Method C
My_object.method_d() # Output: Method D

14
Polymorphism in Python
Polymorphism is one of the key concepts of Object-Oriented Programming (OOP). The word
"polymorphism" is derived from Greek, where "poly" means many and "morph" means forms. In
simple terms, polymorphism allows the same function or method to have different behaviors
based on the object it is acting upon.
Types of Polymorphism in Python
1. Method Overriding
2. Operator Overloading
3. Method Overloading
Method Overriding
Method overriding occurs when a child class provides a specific implementation of a method
that is already defined in its parent class.

Example:
class Animal:
def speak(self):
return "Animal makes a sound"

class Dog(Animal):
def speak(self):
return "Dog barks"

class Cat(Animal):
def speak(self):
return "Cat meows"

# Creating objects
a = Animal()
d = Dog()
c = Cat()

# Calling the speak method


print([Link]()) # Output: Animal makes a sound
print([Link]()) # Output: Dog barks
print([Link]()) # Output: Cat meows

Operator Overloading
Python allows us to redefine how operators like +, -, *, etc., work for user-defined objects.
Example:
class Student:
def __init__(self, marks):
[Link] = marks

def __add__(self, other):


return [Link] + [Link]

s1 = Student(80)
s2 = Student(90)

print(s1 + s2) # Output: 170

15
Method Overloading
Python does not support method overloading like other languages (such as Java or C++), but we
can achieve similar behavior using default arguments.
Example:
class Calculator:
def add(self, a, b, c=0):
return a + b + c

calc = Calculator()
print([Link](10, 20)) # Output: 30
print([Link](10, 20, 30)) # Output: 60

Module in Python:
A module in Python is a file containing Python code (functions, classes, or variables) that can be
reused in other programs. It helps in code reusability and organization. A module is a file that
will contain a set of objects such as functions, variables, classes, etc., to use in your applications.
The modules are useful to reduce the code redundancy by keeping the common functionalities
such as functions, variables, etc., in one place and use it in any interpreter session or python
script.

Creating a Module:
In python, we can create a module by writing the following code in the [Link] file.

def add(x, y):


return x + y
def subtract(x, y):
return x - y
users = ["A", "B", "C"]

If we observe the above code, we created a module (samplemodule) with a combination of


functions and variables.

Import Module:
In python, you can import the module by using the import keyword. To use the module
(samplemodule) that we created in any python script or interpreter, you need to use an import
statement like as shown below.

import samplemodule

16
Python Built-in Modules:
The module is a file that will contain a set of functions, variables, classes, etc., to use in your
applications. Python has a set of built-in modules such as math, os, sys, etc., to use in any
python script file. The built-in modules will load automatically whenever the interpreter starts,
and these modules are available as a part of python libraries.

To see the list of all available built-in modules, execute the help('modules') command in the
python console as shown below.

Get Help on Modules


To get the details about a particular built-in module, you can use the help() method. For
example, after importing the math module, you can call help(math) to get the math module
details in python.

Following is an example of getting the details about the math module in python.
import math
help(math)

Python math Module


The math module in Python provides various mathematical functions, constants, and operations
for performing complex mathematical calculations. It includes functions for logarithms,
trigonometry, exponentiation, rounding, and more.
Importing the Math Module
To use the math module, it must be imported first:
Import math
Examples:
import math
print([Link]) # Output: 3.141592653589793
print(math.e) # Output: 2.718281828459045
print([Link](16)) # Output: 4.0
print([Link](2, 3)) # Output: 8.0
print(math.log10(100)) # Output: 2.0
print([Link](60)) # Output: -0.3048106211022167
print ([Link](5.647)) # Output: 6
print ([Link](5.647)) # Output: 5
print([Link](5)) # Output: 120

Python time and datetime Modules:


Python provides two modules for working with date and time:
time module – Deals with time-related functions.
datetime module – Deals with both date and time operations.

time Module:
The time module in Python provides functions to work with time-related operations like
measuring execution time, delaying execution, and getting the current time.
import time

Getting Local Time ([Link]()):


Returns the current local time as a struct_time object.
import time
local_time = [Link]()
print(local_time)

17
Getting the Current Time ([Link]())
Returns the current time as the number of seconds since January 1, 1970 (Epoch Time).
import time
print([Link]())

Getting Current Date and Time ([Link]())


Returns the current date and time.
import datetime
now = [Link]()
print(now) # Output: 2025-03-06 14:30:45.123456

18

You might also like