0% found this document useful (0 votes)
7 views13 pages

Chapter-9[Module] (1)

This document provides an overview of modules in Python, explaining how to create, use, and import them, along with examples. It covers the use of the datetime module for date manipulation, built-in math functions, and the statistics module for statistical calculations. Additionally, it introduces the random module for generating random numbers and various mathematical functions available in Python's math module.

Uploaded by

jiya23022009
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)
7 views13 pages

Chapter-9[Module] (1)

This document provides an overview of modules in Python, explaining how to create, use, and import them, along with examples. It covers the use of the datetime module for date manipulation, built-in math functions, and the statistics module for statistical calculations. Additionally, it introduces the random module for generating random numbers and various mathematical functions available in Python's math module.

Uploaded by

jiya23022009
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/ 13

Chapter-9 [Module]

What is a Module?

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your


application.

Create a Module

To create a module just save the code you want in a file with the file
extension .py:

Example

Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using


the import statement:

Example

Import the module named mymodule, and call the greeting


function:

import mymodule

mymodule.greeting("Jonathan")
Run Example »

Note: When using a function from a module, use the


syntax: module_name.function_name.
Variables in Module

The module can contain functions, as already described, but also


variables of all types (arrays, dictionaries, objects etc):

Example

Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example

Import the module named mymodule, and access the person1


dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)
Run Example »
Naming a Module

You can name the module file whatever you like, but it must have
the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using


the as keyword:

Example

Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)
Using the dir() Function

There is a built-in function to list all the function names (or variable
names) in a module. The dir() function:

Example

List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Import From Module

You can choose to import only parts from a module, by using


the from keyword.

Example

The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example

Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Run Example »
Note: When importing using the from keyword, do not use the
module name when referring to elements in the module.
Example: person1["age"], not mymodule.person1["age"]

Python Dates

A date in Python is not a data type of its own, but we can import a
module named datetime to work with dates as date objects.

Example

Import the datetime module and display the current date:

import datetime

x = datetime.datetime.now()
print(x)

Date Output

When we execute the code from the example above the result will
be:

2024-12-25 11:14:31.016826

The date contains year, month, day, hour, minute, second, and
microsecond.

The datetime module has many methods to return information


about the date object.

Here are a few examples, you will learn more about them later in
this chapter:

Example

Return the year and name of weekday:

import datetime

x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
Try it Yourself »

Creating Date Objects

To create a date, we can use the datetime() class (constructor) of


the datetime module.

The datetime() class requires three parameters to create a date:


year, month, day.

Example

Create a date object:

import datetime

x = datetime.datetime(2020, 5, 17)

print(x)
Try it Yourself »

The datetime() class also takes parameters for time and timezone
(hour, minute, second, microsecond, tzone), but they are optional,
and has a default value of 0, (None for timezone).

The strftime() Method

The datetime object has a method for formatting date objects into
readable strings.

The method is called strftime(), and takes one parameter, format,


to specify the format of the returned string:

Example

Display the name of the month:

import datetime
x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))
Try it Yourself »

Here are few examples of format codes: #it is a good to remember and can be
used in your projects..

Python Math

Python has a set of built-in math functions, including an extensive


math module, that allows you to perform mathematical tasks on
numbers.
Built-in Math Functions

The min() and max() functions can be used to find the lowest or
highest value in an iterable:

Example
x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)

The abs() function returns the absolute (positive) value of the


specified number:

Example
x = abs(-7.25)

print(x)
Try it Yourself »

The pow(x, y) function returns the value of x to the power of y (xy).

Example

Return the value of 4 to the power of 3 (same as 4 * 4 * 4):

x = pow(4, 3)

print(x)
Try it Yourself »
The Math Module

Python has also a built-in module called math, which extends the list
of mathematical functions.

To use it, you must import the math module:

import math
When you have imported the math module, you can start using
methods and constants of the module.

The math.sqrt() method for example, returns the square root of a


number:

Example
import math

x = math.sqrt(64)

print(x)
Try it Yourself »

The math.ceil() method rounds a number upwards to its nearest


integer, and the math.floor() method rounds a number downwards
to its nearest integer, and returns the result:

Example
import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1
Try it Yourself »

The math.pi constant, returns the value of PI (3.14...):

Example
import math

x = math.pi

print(x)

Python Random Module

Python has a built-in module that you can use to make random
numbers.
The random module has a set of methods:

Python Random random() Metho

Definition and Usage

The random() method returns a random floating number between 0


and 1.

Syntax
random.random()

Example

Return random number between 0.0 and 1.0:

import random

print(random.random())
Try it Yourself »

 Python Random randrange() Method

Definition and Usage

The randrange() method returns a randomly selected element from


the specified range.

Syntax
random.randrange(start, stop, step)
Example

Return a number between 3 and 9:

import random

print(random.randrange(3, 9))
Try it Yourself »

Python Random randint() Method

Definition and Usage

The randint() method returns an integer number selected element


from the specified range.

Note: This method is an alias for randrange(start, stop+1).

Syntax
random.randint(start, stop)

Example

Return a number between 3 and 9 (both included):

import random

print(random.randint(3, 9))

Python statistics.mean() Method

The statistics.mean() method calculates the mean (average) of the


given data set.

Tip: Mean = add up all the given values, then divide by how many
values there are.
Example

Calculate the average of the given data:

# Import statistics Library


import statistics

# Calculate average values


print(statistics.mean([1, 3, 5, 7, 9, 11, 13]))
print(statistics.mean([1, 3, 5, 7, 9, 11]))
print(statistics.mean([-11, 5.5, -3.4, 7.1, -9, 22]))

Python statistics.median() Method

Definition and Usage

The statistics.median() method calculates the median (middle


value) of the given data set. This method also sorts the data in
ascending order before calculating the median.

Tip: The mathematical formula for Median is: Median = {(n + 1) /


2}th value, where n is the number of values in a set of data. In
order to calculate the median, the data must first be sorted in
ascending order. The median is the number in the middle.

Note: If the number of data values is odd, it returns the exact


middle value. If the number of data values is even, it returns the
average of the two middle values.

Syntax
statistics.median(data)

Example

Calculate the median (middle value) of the given data:

# Import statistics Library


import statistics

# Calculate middle values


print(statistics.median([1, 3, 5, 7, 9, 11, 13]))
print(statistics.median([1, 3, 5, 7, 9, 11]))
print(statistics.median([-11, 5.5, -3.4, 7.1, -9, 22]))
Python statistics.mode() Method

Definition and Usage

The statistics.mode() method calculates the mode (central


tendency) of the given numeric or nominal data set.

Syntax
statistics.mode(data)

Example

Calculate the mode (central tendency) of the given data:

# Import statistics Library


import statistics

# Calculate the mode


print(statistics.mode([1, 3, 3, 3, 5, 7, 7 9, 11]))
print(statistics.mode([1, 1, 3, -5, 7, -9, 11]))
print(statistics.mode(['red', 'green', 'blue', 'red']))

Python statistics.stdev() Method

Definition and Usage

The statistics.stdev() method calculates the standard deviation


from a sample of data.

Standard deviation is a measure of how spread out the numbers


are.

A large standard deviation indicates that the data is spread out, - a


small standard deviation indicates that the data is clustered closely
around the mean.

Tip: Standard deviation is (unlike the Variance) expressed in the


same units as the data.

Tip: Standard deviation is the square root of sample variance.

Tip: To calculate the standard deviation of an entire population,


look at the statistics.pstdev() method.
Example

Calculate the standard deviation of the given data:

# Import statistics Library


import statistics

# Calculate the standard deviation from a sample of data


print(statistics.stdev([1, 3, 5, 7, 9, 11]))
print(statistics.stdev([2, 2.5, 1.25, 3.1, 1.75, 2.8]))
print(statistics.stdev([-11, 5.5, -3.4, 7.1]))
print(statistics.stdev([1, 30, 50, 100]))

 These are mathematical functions in Python's math module:


You need to import math before performing this:-
1. fabs(): Returns the absolute value of a number as a float, Syntax:
math.fabs(x), and Example.
import math
print(math.fabs(-5.2))
2. sin(): Returns the sine of a value (in radians), Syntax: math.sin(x), and
Example.
import math
print(math.sin(math.pi/2))

3. cos(): Returns the cosine of a value (in radians), Syntax: math.cos(x),


and Example.
import math
print(math.cos(math.pi))
4. tan(): Returns the tangent of a value (in radians), Syntax: math.tan(x),
and Example.
import math
print(math.tan(0))

You might also like