Unit 4
Unit 4
Unit-4
numbers and mathematical methods in
Python
Outline
Looping
✓ Numbers in Python
✓ Random number functions
✓ Trigonometric functions
✓ Mathematical constants
✓ Dates and times
Numbers in Python
Number data types store numeric values. They are immutable data types.
This means, changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them
You can also delete the reference to a number object by using the del
statement.
i.e. del a or if you have many variables use like del a,b,c
Numbers in Python
Python supports different numerical types:
int (signed integers): are often called just integers or ints (- or + whole numbers with no decimal point).
Integers in Python 3 are of unlimited size.
E.g. x=12345678901234567890123456789012345678901234567890123456789012345678901
Python 2 has two integer types - int and long. There is no 'long integer' in Python 3 anymore.
float (floating point real values) : Also called floats, they represent real numbers and are
written with a decimal point dividing the integer and the fractional parts.
Floats may also be in scientific notation, with E or e indicating the power of 10
E.g. 3.8e2 = 3.8 x 102 = 380).
complex (complex numbers) : are of the form a + bJ, where a and b are floats and J (or j)
represents the square root of -1 (which is an imaginary number).
The real part of the number is a, and the imaginary part is b.
Complex numbers are not used much in Python programming.
E.g. x=3.25j or y=2.35j
Numbers in Python
An integer can be represented in hexa-decimal or octal form or binary.
NB: in order to represent an integer in hexa decimal, start with 0x or 0X always.
in order to represent an integer in octal/ base eight, start with 0o or 0O always.
in order to represent an integer in binary, start with 0b or 0B always.
E.g. num0=0xA0F #represents integer 2575
num1=0XED #represents integer 237
num2=0o34 #represents integer 28
num3 =0O654 #represents integer 428
num4 = 0b1010 #represents integer 10
num5 = 0B1001 #represents integer 9
num6 =0b1010110 #represents integer 86
num=0OADG #impossible
num=0O238 #impossible
num=0b1021 #impossible
Numbers in Python
Number Type Conversion
Python converts numbers internally in an expression containing mixed types to a common type
for evaluation.
Type int(x) to convert x to a plain integer. E.g. int(2.3) #converts to 2
Type long(x) to convert x to a long integer but it can not work in python 3 since no 'long integer'
in Python 3
Type float(x) to convert x to a floating-point number.
E.g. float(2) #converts to 2.0
Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
E.g. complex(2) #converts to (2+0j) or complex(2.22) #converts to (2.22+0j)
Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part
y. x and y are numeric expressions.
E.g. complex(2,3) #converts to (2+3j) or complex(2.22,5) #converts to (2.22+5j) or
complex(5,2.22) #converts to (5+2.22j)
Mathematical functions in Python
Python supports the following built-in functions that perform mathematical calculations.
Functions Descriptions
abs(x) The absolute value of x: the (positive) distance between x and zero.
ceil(x) The ceiling of x: the smallest integer not less than x.
cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y. Deprecated in Python 3; Instead use return (x>y)-(x<y).
exp(x) The exponential of x: ex
fabs(x) The absolute value of x.
floor(x) The floor of x: the largest integer not greater than x.
log(x) The natural logarithm of x, for x> 0.
log10(x) The base-10 logarithm of x for x> 0.
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity.
Mathematical functions in Python
Con…
Functions Descriptions
min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity.
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as
x. The integer part is returned as a float.
pow(x, y) pow(x, y) The value of x**y.
round(x [,n]) x rounded to n digits from the decimal point. Python rounds away from zero as a tie-
breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
x - This is a numeric expression.
n - Represents number of digits from decimal point up to which x is to be rounded. Default is 0.
sqrt(x) sqrt(x) The square root of x for x > 0.
NB: in order to use most of those built in functions, you first import the mathematical library
i.e. import math
Mathematical functions in Python
Examples:
Output:
abs(x) abs(-30) : 30
print ("abs(-30) : ", abs( -30)) abs(15.2) : 15.2
print ("abs(15.2) : ", abs(15.2))
math.ceil(x)
import math
print ("math.ceil(-45.17) : ", math. ceil(- 45.17)) Output:
print ("math.ceil(100.12) : ", math. ceil(100.12)) math. ceil( -45.17) : -45
math. ceil( 100.12) : 101
print ("math.ceil(100.72) : ", math. ceil(100.72))
math. ceil( 100.72) : 101
print ("math.ceil(math.pi) : " , math. ceil( math. pi)) math. ceil( math. pi) : 4
math.exp( x )
import math Output:
print ("math.exp(-45.17) : ", math.exp( -45.17)) math.exp(-45.17) : 2.4150062132629406e-20
print ("math.exp(100.12) : ", math.exp(100.12)) math.exp(100.12) : 3.0308436140742566e+43
print ("math.exp(100.72) : ", math.exp(100.72)) math.exp(100.72) : 5.522557130248187e+43
print ("math.exp(math.pi) : ", math.exp(math.pi)) math.exp(math.pi) : 23.140692632779267
Mathematical functions in Python con…
math.fabs(x)
import math
print ("math.fabs( -45.17) : " , math. fabs(-45.17)) Output:
print ("math.fabs(100.12) : " , math. fabs(100.12)) math. fabs(-45.17) : 45.17
print ("math.fabs(100.72) : " , math. fabs(100.72)) math. fabs(100) : 100.0
print ("math.fabs(math.pi) : ", math. fabs(math. pi)) math. fabs(100.72) : 100.72
math. fabs(math. pi) :
3.141592653589793
math. floor(x)
import math
print ("math.floor(-45.17) : ", math. floor(-45.17))
print ("math.floor(100.12) : " , math. floor(100.12)) Output:
math. floor(-45.17) : -46
print ("math.floor(100.72) : " , math. floor(100.72)) math. floor(100.12) : 100
print ("math.floor(math.pi) : " , math. floor(math. pi)) math. floor(100.72) : 100
math. floor(math. pi) : 3
Mathematical functions in Python con…
math.log(x)
import math
print ("math.log(100.12) : ", math. log(100.12)) Output:
math. log(100.12) : 4.6063694665635735
print ("math.log(100.72) : ", math. log(100.72))
math. log(100.72) : 4.612344389736092
print ("math.log(math.pi) : ", math. log(math. pi)) math. log(math. pi) : 1.1447298858494002
math. log10(x)
import math
print ("math.log10(100.12) : ", math.log10(100.12)) Output:
print ("math.log10(100.72) : ", math.log10(100.72)) math.log10(100.12) : 2.0005208409361854
math.log10(100.72) : 2.003115717099806
print ("math.log10(119) : ", math.log10(119)) math.log10(119) : 2.0755469613925306
print ("math.log10(math.pi) : ", math.log10(math.pi)) math.log10(math.pi) : 0.49714987269413385
max( x, y, z,… )
print ("max(80, 100, 1000) : ", max(80, 100, 1000)) Output:
print ("max(-20, 100, 400) : ", max( -20, 100, 400)) max(80, 100, 1000) : 1000
print ("max(-80, -20, -10) : ", max( -80, -20, -10)) max(-20, 100, 400) : 400
max(-80, -20, -10) : -10
Mathematical functions in Python con…
min(x, y, z, …)
print ("min(80, 100, 1000) : ", min(80, 100, 1000)) Output:
min(80, 100, 1000) : 80
print ("min(-20, 100, 400) : ", min( -20, 100, 400))
min(-20, 100, 400) : -20
print ("min(-80, -20, -10) : ", min( -80, -20, -10)) min(-80, -20, -10) : -80
print ("min(0, 100, -400) : ", min(0, 100, -400)) min(0, 100, -400) : -400
math. modf(x): returns the fractional and integer parts of x in a two-item tuple.
import math
print ("math.modf(100.12) : ", math.modf(100.12)) Output:
math.modf(100.12) : (0.12000000000000455, 100.0)
print ("math.modf(100.72) : ", math.modf(100.72))
math.modf(100.72) : (0.7199999999999989, 100.0)
print ("math.modf(119) : ", math.modf(119)) math.modf(119) : (0.0, 119.0)
print ("math.modf(math.pi) : ", math.modf(math.pi)) math.modf(math.pi) : (0.14159265358979312, 3.0)
math.pow( x, y )
Output:
print ("math.pow(100, 2) : ", math.pow(100, 2)) math.pow(100, 2) : 10000.0
print ("math.pow(100, -2) : ", math.pow(100, -2)) math.pow(100, -2) : 0.0001
print ("math.pow(2, 4) : ", math.pow(2, 4)) math.pow(2, 4) : 16.0
print ("math.pow(3, 0) : ", math.pow(3, 0)) math.pow(3, 0) : 1.0
Mathematical functions in Python con…
round(x [, n]): returns x rounded to n digits from the decimal point.
math. sqrt(x)
import math Output:
math.sqrt(100) : 10.0
print ("math.sqrt(100) : ", math.sqrt(100)) math.sqrt(7) : 2.6457513110645907
print ("math.sqrt(7) : ", math.sqrt(7)) math.sqrt(math.pi) : 1.7724538509055159
Import random
list = [20, 16, 10, 5]; Output:
random.shuffle(list) Reshuffled list : [16, 5, 10, 20]
print ("Reshuffled list : ", list) reshuffled list : [20, 5, 10, 16]
random.shuffle(list)
print ("Reshuffled list : ", list)
uniform (x, y): returns a random float r, such that x is less than or equal to r and r is less than y.
x - Sets the lower limit of the random float.
y - Sets the upper limit of the random float. But if y<x, the lower limit is not work.
import random Output:
Random Float uniform(5, 10) :
print ("Random Float uniform(5, 10) : ", random.uniform(5, 10)) 5.52615217015
Random Float uniform(7, 14) :
print ("Random Float uniform(7, 14) : ", random.uniform(7, 14)) 12.5326369199
Trigonometric functions in Python
Trigonometry functions such as sine, cosine, and tangent can also be calculated using the Python
REPL (Read Evaluate Print Loop) which is used to perform calculations at the Python Prompt.
Python includes the following functions that perform trigonometric calculations.
Functions Descriptions
acos(x) Return the arc cosine of x, in radians
asin(x) Return the arc sine of x, in radians.
atan(x) Return the arc tangent of x, in radians.
atan2(y, x) Return atan(y / x), in radians.
cos(x) Return the cosine of x radians.
hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y)
sin(x) Return the sine of x radians
tan(x) Return the tangent of x radians.
degrees(x) Converts angle x from radians to degrees.
radians(x) Converts angle x from degrees to radians.
Trigonometric functions in Python conn…
Examples: acos(x)
x - This must be a numeric value in range -1 to 1. If x is greater than 1 then it will generate 'math domain
error'.
Import math
print ("acos(0.64) : ", math.acos(0.64))
Output:
print ("acos(0) : ", math.acos(0))
acos(0.64) : 0.876298061168
print ("acos(-1) : ", math.acos(-1)) acos(0) : 1.57079632679
print ("acos(1) : ", math.acos(1)) acos(-1) : 3.14159265359
acos(1) : 0.0
asin(x)
x – must be a numeric value in range -1 to 1. If x is greater than 1 then it will generate 'math domain error'.
import math
print ("asin(0.64) : ", math.asin(0.64)) Output:
print ("asin(0) : ", math.asin(0)) asin(0.64) : 0.694498265627
print ("asin(-1) : ", math.asin(-1)) asin(0) : 0.0
asin(-1) : -1.57079632679
print ("asin(1) : ", math.asin(1)) asin(1) : 1.5707963267
Trigonometric functions in Python conn…
atan(x)
x - must be a numeric value
Import math
print ("atan(0.64) : ", math.atan(0.64)) Output:
print ("atan(0) : ", math.atan(0)) atan(0.64) : 0.569313191101
atan(0) : 0.0
print ("atan(10) : ", math.atan(10)) atan(10) : 1.4711276743
print ("atan(-1) : ", math.atan(-1)) atan(-1) : -0.785398163397
print ("atan(1) : ", math.atan(1)) atan(1) : 0.785398163397
Eg.
import time
print ("ctime : ", time.ctime())
Output:
ctime : Wed Mar 6 09:58:21 2024
Dates and times in Python
Time gmtime([sec]) Method: converts a time expressed in seconds since the epoch to a
struct_time in UTC in which the dst flag is always zero.
If secs is not provided or None, the current time as returned by time() is used.
sec - These are the number of seconds to be converted into structure struct_time
representation and does not return any value.
Eg.
import time
print ("gmtime :", time.gmtime(1455508609.34375))
Output:
gmtime : time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=3,
tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0)
Dates and times in Python
Time localtime([sec]) Method: similar to gmtime() but it converts number of seconds to local
time.
If secs is not provided or None, the current time as returned by time() is used.
The dst flag is set to 1 when DST applies to the given time.
sec - These are the number of seconds to be converted into string representation and does not
return any value.
Eg.
import time
print ("time.localtime() : %s" , time.localtime())
Output:
time.localtime() : %s time.struct_time(tm_year=2024, tm_mon=3, tm_mday=6, tm_hour=10,
tm_min=15, tm_sec=56, tm_wday=2, tm_yday=66, tm_isdst=0)
Dates and times in Python
Time mktime(t) Method: is the inverse function of localtime().
Its argument is the struct_time or full 9-tuple and it returns a floating point number, for
compatibility with time().
If the input value cannot be represented as a valid time, either OverflowError or ValueError
will be raised.
t - This is the struct_time or full 9-tuple.
It returns a floating point number, for compatibility with time().
E.g. import time
t = (2024, 2, 15, 10, 13, 38, 1, 48, 0) # i.e, (tm_year=2024, tm_mon=3, tm_mday=6, tm_hour=10,
tm_min=15, tm_sec=56, tm_wday=2, tm_yday=66, tm_isdst=0)
d=time.mktime(t)
print ("time.mktime(t) : %f" % d)
print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(d)))
Output:
time.mktime(t) : 1707981218.000000
asctime(localtime(secs)): Thu Feb 15 10:13:38 2024
Dates and times in Python
Time sleep(t) Method: suspends execution for the given number of seconds.
The argument may be a floating point number to indicate a more precise sleep time.
The actual suspension time may be less than that requested because any caught signal
will terminate the sleep() following execution of that signal's catching routine.
t - This is the number of seconds for which the execution is to be suspended and does not
return any value.
Eg.
import time
print ("Start : %s" % time.ctime())
time.sleep(5)
Output:
print ("End : %s" % time.ctime())
Start : Wed Mar 6 10:25:30 2024
End : Wed Mar 6 10:25:50 2024
Dates and times in Python
Time strftime(format [,t]) Method: converts a tuple or struct_time representing a time as returned
by gmtime() or localtime() to a string as specified by the format argument.
If t is not provided, the current time as returned by localtime() is used. The format must be a string.
An exception ValueError is raised if any field in t is outside of the allowed range.
t - This is the time in number of seconds to be formatted.
format - This is the directive which would be used to format given time.
The following directives can be embedded in the format string
%a - abbreviated weekday name
%A - full weekday name
%b - abbreviated month name
%B - full month name
%c - preferred date and time representation
%C - century number (the year divided by 100, range 00 to 99)
%d - day of the month (01 to 31)
%D - same as %m/%d/%y
%e - day of the month (1 to 31)
Dates and times in Python
Time strftime(format [,t]) Method: directives con…
%g - like %G, but without the century
%G - 4-digit year corresponding to the ISO week number (see %V).
%h - same as %b
%H - hour, using a 24-hour clock (00 to 23)
%I - hour, using a 12-hour clock (01 to 12)
%j - day of the year (001 to 366)
%m - month (01 to 12)
%M - minute
%n - newline character
%p - either am or pm according to the given time value
%r - time in a.m. and p.m. notation
%R - time in 24 hour notation
%S - second
%t - tab character
%T - current time, equal to %H:%M:%S
Dates and times in Python
Time strftime(format [,t]) Method: directives con…
%u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
%U - week number of the current year, starting with the first Sunday as the first day of the
first week
%V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first
week that has at least 4 days in the current year, and with Monday as the first day of the week
%W - week number of current year, starting with the first Monday as first day of first week
%w - day of the week as a decimal, Sunday=0
%x - preferred date representation without the time
%X - preferred time representation without the date
%y - year without a century (range 00 to 99)
%Y - year including the century
%Z or %z - time zone or name or abbreviation
%% - a literal % character
Dates and times in Python
Time strftime(format [,t]) Method: examples
Eg.
import time
t = (2024, 12, 31, 10, 39, 45, 1, 48, 0)
t = time.mktime(t)
print (time.strftime("%b %d %Y %H:%M:%S", time.localtime(t)))
print (time.strftime("%B %D %Y %H:%M:%S", time.localtime(t)))
print (time.strftime("%B %D %Y %H:%M:%S", time.localtime(955458)))
Output:
Dec 31 2024 10:39:45
December 12/31/24 2024 10:39:45
January 01/12/70 1970 04:24:18
Dates and times in Python
Time strptime(string[, format]) Method: parses a string representing a time according to a format.
The return value is a struct_time as returned by gmtime() or localtime().
The format parameter uses the same directives as those used by strftime(); it defaults to
"%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().
string - This is the time in string format which would be parsed based on the given format.
format - This is the directive which would be used to parse the given string.
Eg.
import time
struct_time = time.strptime("30 12 2024", "%d %m %Y")
print ("tuple : ", struct_time)
Output:
tuple : time.struct_time(tm_year=2024, tm_mon=12, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=0, tm_yday=365, tm_isdst=-1)
Dates and times in Python
Time time() Method: returns the time as a floating point number expressed in seconds since
the epoch, in UTC.
Eg.
import time
print ("time.time(): %f " % time.time())
print (time.localtime(time.time()))
print (time.asctime(time.localtime(time.time())))
Output:
time.time(): 1709791146.462177
time.struct_time(tm_year=2024, tm_mon=3, tm_mday=7, tm_hour=8, tm_min=59, tm_sec=32, tm_wday=3,
tm_yday=67, tm_isdst=0)
Thu Mar 7 09:00:04 2024
Dates and times in Python
Time tzset() Method: resets the time conversion rules used by the library routines. The
environment variable TZ specifies how this is done.
The standard format of the TZ environment variable is (whitespace added for clarity):-
std offset [dst [offset [,start[/time], end[/time]]]]
std and dst: Three or more alphanumerics giving the timezone abbreviations.
These will be propagated into time.tzname.
import time
import os
# Define TZ environment variable
os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0’
#time.tzset() # not available in Windows
print (time.strftime('%X %x %Z'))
os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0’
#time.tzset()
print (time.strftime('%X %x %Z'))
Output:
09:17:15 03/07/24 E. Africa Standard Time
09:17:45 03/07/24 E. Africa Standard Time
Dates and times in Python
Time module attributes
There are two important attributes available with time module.
time.timezone: is the offset in seconds of the local time zone (without DST) from UTC (>0
in the Americas; <=0 in most of Europe, Asia, Africa).
time.tzname: is a pair of locale-dependent strings, which are the names of the local time zone
without and with DST, respectively.
import time
time.timezone
Output:
time.tzname -10800
'E. Africa Standard Time', 'E. Africa Daylight Time')
Dates and times in Python
The calendar module: supplies calendar-related functions, including functions to print a text
calendar for a given month or year.
By default, calendar takes Monday as the first day of the week and Sunday as the last one.
To change this, call the calendar.setfirstweekday() function.
Function with Description
calendar.calendar(year,w=2,l=1,c=6): Returns a multiline string with a calendar for year year formatted
into three columns separated by c spaces. w is the width in characters of each date; each line has length
21*w+18+2*c. l is the number of lines for each week.
calendar.firstweekday( ): Returns the current setting for the weekday that starts each week. By default,
when calendar is first imported, this is 0, meaning Monday.
calendar.isleap(year): Returns True if year is a leap year; otherwise, False.
calendar.leapdays(y1,y2): Returns the total number of leap days in the years within range(y1,y2).
calendar.month(year,month,w=2,l=1): Returns a multiline string with a calendar for month month of year
year, one line per week plus two header lines. w is the width in characters of each date; each line has length
7*w+6. l is the number of lines for each week.
Dates and times in Python
The calendar module: conn…
Function with Description
calendar.monthcalendar(year,month): Returns a list of lists of ints. Each sublist denotes a week. Days
outside month of year year are set to 0; days within the month are set to their day-ofmonth, 1 and up.
calendar.monthrange(year,month): Returns two integers. The first one is the code of the weekday for the
first day of the month month in year year; the second one is the number of days in the month.
Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.
calendar.prcal(year,w=2,l=1,c=6): Like print calendar.calendar(year,w,l,c).
calendar.prmonth(year,month,w=2,l=1): Like print calendar.month(year,month,w,l).
calendar.setfirstweekday(weekday): Sets the first day of each week to weekday code weekday. Weekday
codes are 0 (Monday) to 6 (Sunday).
calendar.timegm(tupletime): The inverse of time.gmtime: accepts a time instant in time-tuple form and
returns the same instant as a floating-point number of seconds since the epoch.
calendar.weekday(year,month,day): Returns the weekday code for the given date. Weekday codes are 0
(Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).
Dates and times in Python
Other Modules & Functions
Use the list of other important modules and functions to play with date & time in
Python:
The datetime Module
The pytz Module
The dateutil Module