Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CIT 101 Py Lesson 6 Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Bachelor of Applied Information Technology

Degree Programme – (DAIT)

CIT101 Programming Fundamentals


Lesson 5

Python Modules and Packages


Python organizes its software into modules. This enables Python to keep its components (Objects) in a
meaningful way. It also facilitates Python Objects to communicate in an effective manner, the use of
identifiers effectively, and the reuse of code etc.

Don’t forget that every object in Python has a unique identity, a type, a value, behaviours and an address in
memory. So at the top level you get a collection of packages. A package can contain sub-packages and
modules.

So far we have experienced the use of a few built-in functions such as print(), input(), int(), float(), bool(),
abs(), round() etc. We also have discussed a very little about structures such as ‘list’, ‘tuple’, ‘dict’ and ‘set’
and their use. These things are readily available for use as a built-in part of the Python’s Interactive shell.

Python Interactive Shell


(Software) Standard
Library

import Builtins Core


(Software)
Python 3rd party
>>> User Interaction with the shell (Software)
import
User Applications: PIP Install
------------
------------
User’s world
Python’s world Python Developers’ world

Python’s Interactive shell is the interface of Python through which we interact with Python. We give
commands to solve our problems and Python provides answers to them.
100000
Suppose if you want to know how many digits are there in 2 (Your Problem), you present it to Python as
follows and Python will provide the solution as 301030 in mostly 2 to 3 seconds.

>>> print(len(str(2**1000000)))
301030

Page 1 of 9
Built-in module
Basically the built-in module contains the following:

 built-in functions
 built-in constants
 built-in types (There are 14 types and we have studied about 7 (essentials)
 built-in exceptions

Exception

An exception is an event which occurs during the execution of a program


that disrupts the normal flow of a program.

In addition to ‘built-ins’ Python contains many more things. Exception - Runtime Slip
Some of them belong to Python’s Standard Library.

Standard Library
Python’s Standard Library itself contains a wide range of modules. As they are not integrated into Python’s
shell we have to import them as and when required.

Modules contain program elements such as ‘classes’, ‘functions’, ‘constants’ , ‘variables’ or even ‘bock of
codes’

Python Standard Library contains well over 320 different modules at present. They provide different services
to Python users. There may be many modules to do the same thing. But their objectives and purposes are
different.

Consider the following example.

Try 1: Use the normal way of addition to calculate 0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 (add 0.1 10
times.) Issue the following command and look at the result.

>>> .1+.1+.1+.1+.1+.1+.1+.1+.1+.1 # Add 0.1 10 times


0.9999999999999999 # Oh God! Expected result is 1.0 but we got an unexpected result

Try 2: Use the built-in function sum() to calculate 0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 (add 0.1 10
times.) Issue the following command and look at the result.

>>> sum([.1,.1,.1,.1,.1,.1,.1,.1,.1,.1]) # Add 0.1 10 times using sum() function


0.9999999999999999 # Oh God! The same result

Python is not wrong! If Python is wrong, then other


You are wrong! languages are also wrong! This is the way that the
computers work. (Computers work according to the
way that they have been programmed.)

Try 3: Use a function available in the standard library. So we are going to use ‘fsum()’ in the math module.
Since the math module is not pre-loaded we have to import it.

To calculate 0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 (add 0.1 10 times.) issue the following command


and look at the result.

>>> import math


>>> math.fsum([.1,.1,.1,.1,.1,.1,.1,.1,.1,.1]) # Add using ‘fsum’
1.0 # Got the expected result

Page 2 of 9
Importing Modules

Third Party Libraries


Python also uses a large number of third party modules. They are pre-written packages available with
Python developers. Most of them are available free of charge. If we want to use them you have to install
them using package manager software. Eg. ‘pip3’ for Python version 3

(I will discuss more about ‘pip3’ when you need it. So don’t’ worry about it now)

Note: If you want to get a list of modules in the standard Library, then issue the following command.

>>> help('modules')

User’s own modules and functions

The users can create their own modules and functions and make their own package.

Name Convention of a Module


1. Python modules use short identifiers with all lowercase characters.

2. Python modules use .py extension which is also in lowercase.

Using the Standard Library


Functions in the ‘math’ module

Let us learn few functions in the ‘math’ module.

1. sqrt(x) => Returns the square root of x (x>0). x can be an integer or a floating point number

Examples:

>>> import math


>>> math.sqrt(4) # Display the square root of 4 (Integer)
2.0

>>> math.sqrt(4.361) # Display the square root of 4.361 (Floating point number)
2.0883007446246817
>>> math.sqrt(12*0.03/5) # Display the square root of the given expression
0.2683281572999748

N.B. There is no function available in the in built-in module to find the square root of a number.

Don’t forget that there is an invisible Super Power behind you that is your common sense.

Page 3 of 9
2. ceil(x) => Returns ceiling value of x. That is the smallest integer  x. x can be an integer or a
floating point number.

Note: ceil() returns an integer value

Examples:

>>> import math


>>> math.ceil(12) # Display the ceiling value of integer 12
12

>>> math.ceil(-12) # Display the ceiling value of integer -12


-12

>>> math.ceil(12.3) # Display the ceiling value of 12.3 which is 13


13

>>> math.ceil(11.9) # Display the ceiling value of 11.9 which is 12


12

>>> math.ceil(-11.9) # Display the ceiling value of -11.9 which is -11


-11

3. floor(x) => Returns floor value of x. That is the largest integer  x. x


can be an integer or a floating point number.

Note: floor() returns an integer value

Examples:

>>> math.floor(12) # Display the floor value of integer 12


12

>>> math.floor(-12) # Display the floor value of integer -12


-12

>>> math.floor(12.9) # Display the floor value of 12.9


12

>>> math.floor(12.01) # Display the floor value of 12.01


12

>>> math.floor(-12.99) # Display the floor value of -12.99


-13

4. trunc(x) => Returns the real value of x truncated to an integer. (Removes the decimal part
completely.)

Note: trunc() returns an integer value

Examples:

>>> math.trunc(12.99) # Display the integer part of 12.99


12

>>> math.trunc(-12.99) # Display the integer part of -12.99


-12

>>> math.trunc(12.00001) # Display the integer part of 12.00001


12

Page 4 of 9
Note: To verify that (trunc() returns an integer value

>>> x = 12.001 # x is ‘float’.


>>> type(x) # Check the type of x
<class 'float'> # it’s ‘float’

>>> y = math.trunc(x) # Get the integer part of x, let it be y


>>> type(y) # Check the type of y
<class 'int'> # it’s integer

5. fsum(Iterable) => Returns an accurate floating point sum of values in the iterable.

Examples:

>>> math.fsum((.2,.5,.9,1.6,.002,7)) # Get the accurate sum


10.202
Note: To verify that ‘fsum’ is more accurate

Using Normal addition and add 0.3 ten times

>>> .3+.3+.3+.3+.3+.3+.3+.3+.3+.3
2.9999999999999996 # We expect 3.0 – not accurate

Use sum() function and add 0.3 ten times

>>> sum([.3,.3,.3,.3,.3,.3,.3,.3,.3,.3])
2.9999999999999996 # We expect 3.0 – not accurate

Use fsum() function and add 0.3 ten times

>>> math.fsum([.3,.3,.3,.3,.3,.3,.3,.3,.3,.3])
3.0 # Exactly 3.0 which is accurate

6. factorial(x) => Returns the factorial of a positive integer.

Note: factorial of a number, as defined in mathematics is as follows.

Factorial is the product of all positive integers less than or equal to a given positive integer.
We write factorial n as n! = n.n-1.n-2.n-3. … 3.2.1

Thus
1! = 1
2! = 2x1 = 2
3! = 3x2x1 = 6
4! = 4x3x2x1 = 24
5! = 5x4x3x2x1 = 120

Manual calculations become difficult as it comes to large integers. So we use Python to do it.
Examples:

>>> math.factorial(5) # Display factorial 5


120

>>> math.factorial(50) # Display factorial 5


30414093201713378043612608166064768844377641568960512000000000000

Calculate 100000! and notice the power of Python.

Page 5 of 9
7. gcd(* integers) => Returns the greatest common denominator of the specified integer arguments.

>>> math.gcd(15,50) # Display greatest common denominator of 15 and 50


5

>>> math.gcd(12,24) # Display greatest common denominator of 12 and 24


12

>>> math.gcd(12,48,32,64) # Display greatest common denominator of 12, 48,32 and 64


4

8. lcm(* integers) => Returns the least common multiplier of the specified integer arguments.

>>> math.lcm(*[12,24,18]) # Display least common multiplier of 12,24 and 18


72

>>>math.lcm(*(3,4,12,24,36)) # Display least common multiplier of 3,4,12, 24 and 36


72

9. prod(iterable, start = 1) => Returns the product of all elements in the input iterable. Default
value of start = 1

>>> math.prod([5,10,15]) # Display the product of 5,10,15. i.e. 5x10x15


750

>>> math.prod([5,10,15],start = 3) # Display the product of 5,10,15. i.e.3x5x10x15


2250

10. exp(x) => Returns ‘e’ raised to the power x. e = 2.718281…


5
>>> math.exp(5) # Display the value of e (Mathematicians and engineers often use (‘e’)
148.4131591025766

Lazy man’s Paradise - 1

51451872591913119192091351920851916554156129782019172111854

11. Value of ‘e’

The number e, sometimes called Euler's number, is an important mathematical constant approximately
equal to 2.71828. It is one of the universal constants. The value of ‘e’ used by Python is as follows. ‘e’ is an
irrational number.

>>> math.e # Display an approximate value of ‘e’


2.718281828459045

12. Value of ‘’

 is the ratio of the circumference of any circle to the diameter of that circle. The value of pi is approximately
3.141592... (Can be approximated crudely to 22/7 which is not accurate but 355/113 is more accurate)  is
an irrational number. It is one of the universal constants. The value use by Python is as follows.

>>> math.pi # Display an approximate value of ‘’


3.141592653589793

Page 6 of 9
13. log(x [,base]) => Returns the natural logarithm for x.

>>> math.log(math.e) # Display an approximate value of loge(e)


1.0

>>> math.log(10) # Display an approximate value of loge(10)


2.302585092994046
>>> math.log(0.0123) # Display an approximate value of loge(0.0123)
-4.398156016603766

>>> math.log(1,10) # Display the value of log10(1)


0.0

>>> math.log(100,10) # Display the value of log10(100)


2.0

14. log10(x) => Returns the base 10 logarithm more accurate than log(x, 10).

>>> math.log10(1000) # Display the value of log10(1000)


3.0

>>> math.log(377.0123,10) # Display the value of log10(377.0123) using log() function


2.5763555192641165

>>> math.log10(377.0123) # Display the value of log10(377.0123) using log10() function


2.576355519264117 # More accurate

Lazy man’s Paradise - 2

Did you read the number given in Lazy man’s Paradise – 1?

If you are lazy you don’t bother to read it.

Just by ignoring it how do you know whether it contains a valuable thing?

Laziness is nothing but a habit of resting before you get tired.

15. pow(x, y) => Returns x raised to the power y.

>>> math.pow(123.45,3) # Display the value of 123.45 to the power 3 using pow()
1881365.963625

>>> 123.45**3 # Display the value of 123.45 to the power 3 using **


1881365.963625

>>> math.pow(123.45,15) # Display the value of 123.45 to the power 3 using pow()
2.3570370761335754e+31

>>> 123.45**15 # Display the value of 123.45 to the power 15 using **


2.3570370761335754e+31

Page 7 of 9
A
16. hypot(*coordinate) => Returns the hypotenuse of a right angled triangle.
C = (a2+b2)
b Hypotenuse

C B
a
>>> math.hypot(3,4) # Display the hypotenuse of the right angled triangle whose other two sides are 3 and 4.
5.0

>>> math.hypot(9,12) # Display the hypotenuse of the right angled triangle whose other two sides are 9 and 12.
15.0

>>> math.hypot(3.4,5.6) # Display the hypotenuse of the right angled triangle whose other two sides are 3.4 and 5.6.
6.551335741663681

17. dist(p, q) => Returns the Euclidean distance of two points p and q.

y Euclidean Distance between two Points.


Distance between Two points P(x1,y1) and Q(x2,y2)
Q (x2,y2)
PQ2 = PR2 + RQ2
y2-y1
R PQ = [(x2-x1)2 + (y2-y1)2 ]
P (x1,y1) x2-x1

x Manhattan Distance between two Points.


o
The distance between two points measured along axes at right angles.
Manhattan Distance between two Points = |x2-x1| + |y2-y1|.

The Euclidean distance between P(3,4) and Q(6,8) = [(6-3) + (8-4) ] = (3 + 4 ) = (9+16) = 5
2 2 2 2

>>> math.dist([6],[3]) # Display the x component of the Manhattan distance between P(3,4) and Q(6,8)
3.0

>>> math.dist([4],[8]) # Display the y component of the Manhattan distance between P(3,4) and Q(6,8)
4.0

>>> math.dist([3,4],[6,8]) # Display the Euclidean distance between P(3,4) and Q(6,8)
5.0

>>> a = (1,3,5) # P(1,3,5) are the special coordinates of a point P in 3D space


>>> b = (4,6,8) # Q(1,3,5) are the special coordinates of a point Q in 3D space
>>> math.dist(a,b) # Display the Euclidean distance between P and Q
5.196152422706632

Angular Measurements

We are accustomed to measure an angle in degrees (e.g. 30 ). But in technology mostly we measure angles

in ‘radians’. (E.g. 30 = 0.523599 rad ) 
180 =  radians
Therefore we use the following conversion:

1 = /180 radians
18. degrees(x) => Returns the degree for a given value of x in radians.

>>> math.degrees(0.5236) # Convert 0.5236 radians to degrees


30.0000701530499

>>> math.trunc(math.degrees(0.5236)) # Convert 0.5236 radians to degrees (nearest integer)


30

>>> math.trunc(math.degrees(math.pi/2)) # Convert /2 radians to degrees (nearest integer)


90

Page 8 of 9
19. radians(x) => Returns the radians for a given value of x in degrees.

>>> math.radians(30) # Convert 30 degrees to radians


0.5235987755982988

>>> math.radians(180) # Convert 180 degrees to radians


3.141592653589793

Lazy man’s Paradise - 3


You ignored reading the number appeared in Lazy man’s Paradise – 1 because you
were lazy to read it.

You ignored it because you didn’t understand it at once.

The fox at least tried several


times before giving it up

Basic Trigonometric Ratios C


For a given right angled triangle we can define three basic ratios Hypotenuse
namely ‘sine’, cosine and ‘tangent’ in relation to the angle . b
a
Opposite side
sin  = a/b 
A B
cos  = c/b c
Adjacent side
tan  = a/c

20. sin(x) => Return the sine of x radians.

# Display sin(30 )  30 = 180 / 6 = /6


0 0 0
>>> math.sin(math.pi/6)
0.49999999999999994

# Display sin(60 )  60 = 180 / 3 = /3


0 0 0
>>> math.sin(math.pi/3)
0.8660254037844386

# Display sin(90 )  90 = 180 / 2 = /2


0 0 0
>>> math.sin(math.pi/2)
1.0

21. cos(x) => Return the cosine of x radians.

# Display sin(60 )  60 = 180 / 3 = /3


0 0 0
>>> math.cos(math.pi/3)
0.5000000000000001

# Display sin(45 )  45 = 180 / 4 = /4


0 0 0
>>> math.cos(math.pi/4)
0.7071067811865476

22. tan(x) => Return the tangent n of x radians.

# Display tan(45 )  45 = 180 / 4 = /4


0 0 0
>>> math.tan(math.pi/4)
0.9999999999999999

# Display tan(60 )  60 = 180 / 3 = /3


0 0 0
>>> math.tan(math.pi/3)
1.7320508075688767

Page 9 of 9

You might also like