What Are Python Modules
In addition to Python’s built-in functions, Python distribution has a library of built-in code, called modules. Python Modules incorporate complex functionality such as the trigonometric and logarithmic functions, the code for which would be difficult to develop yourself.
Functions Recap
If the program needs to do a certain group of statements in many places in the program, you can group these set of statements in a function. The function can then be called from many places in your program. The function will do the computations on the data passed as arguments to the function from your main program. Python provides many built-in functions. You have come across a few of them like random()
, format()
, max()
, min()
, etc. in Python Functions 1 and Python Function 2 chapters.
Python Modules
As the programs become bigger and more complex such as computer games programs, or programs to solve math, biology, or physics problems, it becomes necessary to have several functions handy that have access to trigonometric functions (sine, cosine, tangent, logarithmic functions, etc.) just to name a few.
As an example, it would be hard to develop algorithms for calculating the sine of an angle and then code it in Python. Python Modules solve this problem by providing such code in ready-to-use modules. Python Modules make your program modular, less unwieldy, and easier to read and understand.
Python Modules vs. Functions
One of the differences between functions and modules is that functions can be called by your program using just the function’s name. Modules, on the other hand, need to be imported using the import
statement before their use.
Python Standard Library
Python comes with a library of standard modules. These modules are described in a document, called the Python Library Reference. Some of these modules are built into the Python interpreter. The Python Library Reference Manual describes the standard library that is distributed with Python.
Python modules can be combined with your code by importing them by their name. Python’s standard library contains built-in modules that provide standardized solutions for many problems that occur in everyday programming. We will discuss a few of the modules in this chapter. The Python library also contains built-in modules (written in C) that provide access to system functionality such as file I/O. We will not discuss these on this website.
Python Modules – How to Import Them
Python module is a file that groups functions, classes, variables, and Python objects.
You can refer to the whole list of library modules here.
<a href=”https://docs.python.org/3/library/“>
You can also display all available modules by using the following command in the Python IDLE shell.
>>> help
(‘modules’)
Python’s built-in functions are automatically loaded when the Python interpreter starts. You have already seen some of these functions, like print()
in the Printing in Python chapter. Unlike functions, Python modules must be imported before you can use them in your programs using the below statement.
>>> import
module_name
We will introduce only a few Python modules in this chapter. We will start with the Python Math Module,
Math Module
The math module contains math functions such as trigonometric functions, logarithmic functions, angle conversion (degrees/radians), etc. The Python math module has 42 objects including 40 functions and two numbers “e” and “pi”. We present below a few of the objects available in the math module.
To get access to the math module’s objects to use in your programs, we first import the math module by typing the following statement in the IDLE shell.
>>> import
math
Then, to access some object inside the math module, you type the following statement:
math.object
where “object” is the name of the function you intend to use.
Below are a few functions in the math module’s objects and example programs.
Math Module Square Root Function
math
.sqrt(x)
This function returns the square root of x.
The following example program finds the square root of numbers 1 through 4 by two methods.
- using procedural programming techniques, we learned in previous chapters.
- using math module’s
sqrt()
method.
PROGRAM EXAMPLE: math FUNCTION math.sqrt(x)
>>> # 1) Using procedural programming
>>> for x in range(1,5):
sqrt = x**0.5
print('Square root of ' , x , 'is = ' , sqrt)
Square root of 1 is = 1.0
Square root of 2 is = 1.4142135623730951
Square root of 3 is = 1.7320508075688772
Square root of 4 is = 2.0
>>>
>>> import math
>>> # Now use math module sqrt() method to find square root
>>> for x in range (1,5):
sqrt = math.sqrt(x)
print('Square root of ' , x , 'is = ' , sqrt)
Square root of 1 is = 1.0
Square root of 2 is = 1.4142135623730951
Square root of 3 is = 1.7320508075688772
Square root of 4 is = 2.0
>>>
Math Module Angle Conversion Function
math.degrees
(x)
This function converts angle ‘x’ from radians to degrees.
math.radians
(x)
This function converts angle ‘x’ from degrees to radians.
- In the example below, we convert an angle of 30 degrees to radians.
- The second program converts an angle pi/4 radian to degrees.
PROGRAM EXAMPLE: ANGLE CONVERSION (RADIAN – DEGREES)
>>> # This code converts angles in degrees to radians
>>> import math
>>> math.radians(30)
0.5235987755982988
>>>
>>> # This code converts angle (pi/4) from radians to degrees.
>>> math.degrees(math.pi/4)
45.0
>>>
Constants in Math Module
The math module has the mathematical constant pi (π). To get the value of pi, write the following statement.
math.pi
The mathematical constant π = 3.141592… is an irrational number. The constant π is the ratio of a circle’s circumference and its diameter.
Irrational numbers were defined in Enrichment: Number Theory in the Input and Output chapter.
In the program below, we use the constant pi (π) to find the circumference of a circular jogging track whose diameter is 100 meters. The circumference of a circle with diameter ‘d’ is equal to π x d.
In this program, we first import the Python math module and then use the math pi constant to calculate the circumference.
PROGRAM EXAMPLE: math MODULE CONSTANT pi
>>> # Find the circumference of a circle of diameter = d
>>> # The circumference of a circle = π times diameter
>>> # in this example the diameter, d = 100 meters
>>> d = 100
>>> import math
>>> circumference = math.pi*d
>>> print('The circumference of a circular jogging track of 100 meters diameter = ', circumference)
The circumference of a circular jogging track of 100 meters diameter = 314.1592653589793
>>>
Math Module Constant ‘e’
math.e
The math module contains another constant known as Euler’s number. It is denoted by ‘e’ and is the base of the natural logarithm. This mathematical constant e = 2.718281
Random Module
As a kid, you might recall playing Snakes and Ladders. In this game, you roll a die, which comes face-up with a number between 1 and 6. This number is generally different every time you roll the dice. Thus, the number coming face-up is random. Games like Snakes and Ladders are called games of chance that depend on some random event happening.
Now suppose you are developing a Python Snakes and Ladders game or any game that depends on chance. Every time your program asks to repeat an event, the result should be randomly different.
From the above, you see, when you start to develop computer games, your program needs to provide randomness in the result (for example the dice outcome). Computer game programs also require randomness to the objects on the screen in a fast-moving video game. Without randomness, the games’ outcome will become deterministic. Therefore, programs for games use randomization extensively.
How do we get randomness in our programs?
Python has a built-in module called random that will generate a random number every time the program statement asks for it. The random module uses the pseudo-random generator function.
random() Function
The random module has a function random()
that generates a floating point random number between 0.0 and 1.0.
You call this function by typing
random.random()
on Python IDLE shell.
Here is an example that generates a random number. Note that every time you call the random()
function, the function returns a different number.
PROGRAM EXAMPLE: random() FUNCTION
>>> # Import Python random module
>>> import random
>>> # Use random module function random()
>>> # to generate floating point number between 0.0 and 1.0
>>> random.random()
0.5962459412624741
>>> random.random()
0.22505654101574057
>>>
randint() Function
The random module has another function, called randint()
. random.randint(x,y)
generates random number integers between two parameters x and y specified between the open and closing parentheses. The generated random number is >= x and <= y.
In the program below, we will emulate the roll of a dice. We will specify parameters (x, y) as (1, 6). Thus, the randint(1,6)
will generate a random integer number between 1 and 6 inclusive. Let us write a short program to see how the randomint(x,y)
function works.
PROGRAM EXAMPLE: randint() FUNCTION
>>> import random
>>> # now let us generate a random number between 1 and 6 to simulate the dice.
>>>
>>> dice = random.randint(1,6)
>>> print('The roll of the dice this time is = ', dice)
The roll of the dice this time is = 3
>>> # Let us roll the dice again.
>>> y = random.randint(1,6)
>>> print('The roll of the dice second time is = ', dice)
The roll of the dice second time is = 1
>>>
Note that we rolled the dice two times. Each time we got a different number.
Number Guessing Game
Here is a number-guessing game. In this game, you are supposed to guess the number selected by the computer. In the program below, we first import the Python module named ‘random’
. Then, we use the random module’s function named randint()
that randomly returns an integer within a range specified inside the parenthesis. For example, random.randint(1,10)
will return one number between 1 and 10. Every time you ask the randint()
function to select a number, the number selected will be randomly different.
PROGRAM EXAMPLE: NUMBER GUESSING GAME
print('Guess the number')
# This game randomly select one number between 1 and 10
# The player needs to guess the number in fewer than ten attempts.
import random
number = random.randint(1,10)
# Function randint() returns a random number between 1 and 10.
# Initialize the number of chances the player gets to zero.
chances = 0
print('Guess a number (between 1,10):')
# The player is asked to input a guess for the number.
# Note the use of 'int' to convert number input
# by the player from string to integer
while chances < 10:
guess = int(input())
if guess == number:
print('Great. You guessed the number correctly.')
break # Break out of the loop if the guessed number. is correct
elif guess < number:
print('The number you guessed is too low')
else:
print('The number you guessed is too high')
# Increment the counter 'chances' to keep track of guess attempts.
chances = chances + 1
if not chances < 10: # If counter > 10, print the below message.
print('Game over. Sorry, you were not able to guess the number.')
Here is the output of the game:
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
========= RESTART: C:/Users/Desktop/Python_prgms/Guessnumbers_1.py ========
Guess the number
Guess a number (between 1,10):
5
The number you guessed is too high
1
Great. You guessed the number correctly.
>>>
========= RESTART: C:/Users/Desktop/Python_prgms/Guessnumbers_1.py ========
Guess the number
Guess a number (between 1,10):
5
The number you guessed is too high
1
The number you guessed is too low
3
The number you guessed is too low
4
Great. You guessed the number correctly.
>>>
Python Time Module
Python comes with a module called time. This module provides various time-related functions. The time module has many built-in functions. We will use the one listed below (sleep function).
time.sleep(sec) Function
sleep()
function suspends the execution of the calling thread for the given number of seconds. suspending the thread is necessary, otherwise, the image on the screen will move so fast that you may not be able to see it. We will use this time module in our programs in the next few chapters.
Python os Module
The python os module is discussed in detail along with Sprites.
Enrichment: Geometry
More about Angles (Degrees and Radians)
If ‘r’ is the radius of a circle, we know that the circumference of a circle is equal to 2 x π x r.
In a circle, if you measure the segment of the circumference equal to its radius, the angle subtended by the segment on the center of the circle is defined as one radian. Since the circumference of the circle is equal to 2 x π x r, there are (2 x π x r)/r = 2 x π radians angle subtended at the center of the circle by the whole circumference. In terms of degrees, the total angle subtended at the center by the complete circumference is 360 degrees. See the figure below. Thus, we conclude that 2 x π radians = 360 degrees, or π radians = 180 degrees.
Since the value of π = 3.14159, one radian = 180 / 3.14159 = 57.29 degrees.
Copyright © 2019 – 2021 softwareprogramming4kids.com
All Rights Reserved