Importing libraries - Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

8. Importing libraries

This chapter demonstrates how to code pre-defined library functionality into your programs.

Inspecting Python

Doing mathematics

Calculating decimals

Telling time

Running timers

Summary

Inspecting Python

Python includes “sys” and “keyword” modules that are useful for interrogating the Python system itself. The keyword module contains a list of all Python keywords in its kwlist attribute and provides an iskeyword() function if you want to test any word.

You can explore the many features of the “sys” module and indeed any feature of Python using the Interactive Mode help system. Just type help() at the >>> prompt to start the Help system, then type sys at the help> prompt that appears.

Perhaps, most usefully, the “sys” module has attributes that contain the Python version number, interpreter location on your system, and a list of all directories where the interpreter seeks module files

– so if you save module files in any of these directories you can be sure the interpreter will find them.

image

system.py

imageStart a new program by importing the “sys” and “keyword” modules to make their features available

import sys , keyword system.py

imageNext, add a statement to display the Python version

print( ‘Python Version:‘ , sys.version )

imageNow, add a statement to display the actual location on your system of the Python interpreter

print( ‘Python Interpreter Location:‘ , sys.executable )

imageThen, add statements to display a list of all directories where the Python interpreter looks for module files

print( ‘Python Module Search Path: ‘ )

for folder in sys.path :

print( folder )

imageFinally, add statements to display a list all the Python keywords

print( ‘Python Keywords: ‘ )

for word in keyword.kwlist :

print( word )

imageSave and then run the program – to see details of the Python version on your own system

image

image

The first item on the Python search path is your current directory – so any file within there or within any subdirectories you make there will be found by the Python interpreter.

image

Spend a little time with the Interactive Mode help utility to discover lots more about Python.

Doing mathematics

Python includes a “math” module that provides lots of functions you can use to perform mathematical procedures once imported.

The math.ceil() and math.floor() functions enable a program to perform rounding of a floating point value specified between their parentheses to the closest integer – math.ceil() rounds up and math.floor() rounds down but the value returned, although an integer, is a float data type rather than an intdata type.

The math.pow() function requires two arguments to raise a specified value by a specified power. The math.sqrt() function, on the other hand, simply requires a single argument and returns the square root of that specified value. Both function results are returned as a numeric value of the float data type.

image

Integers can be cast from the int data type to the float data type using the float() function and to the string data type using the str() function.

Typical trigonometry can be performed using functions from the math module too, such as math.sin(), math.cosin() and math.tan().

Additionally, Python includes a “random” module that can be used to produce pseudo random numbers once imported into a program.

The random.random() function produces a single floating-point number between zero and 1.0. Perhaps, more interestingly, the random.sample() function produces a list of elements selected at random from a sequence. This method requires two arguments to specify the sequence to select from, and the length of the list to be produced. As the range() function returns a sequence of numbers, this can be used to specify a sequence as the first argument to the random.sample() function – so it will randomly select numbers from that sequence to produce a list in which no numbers repeat.

image

maths.py

imageStart a new program by importing the “math” and “random” modules to make their features available

import math , random

imageNext, add statements to display two rounded values

print( ‘Rounded Up 9.5:‘ , math.ceil( 9.5 ) )

print( ‘Rounded Down 9.5:‘ , math.floor( 9.5 ) )

imageNow, add a statement to initialize a variable with an integer value

num = 4

imageAdd statements to display the square and square root of the variable value

print( num , ‘Squared:‘ , math.pow( num , 2 ) )

print( num , ‘Square Root:‘ , math.sqrt( num ) )

imageThen, add a statement to produce a random list of six unique numbers between one and 49

nums = random.sample( range( 1, 49 ) , 6 )

imageFinally, add a statement to display the random list

print( ‘Your Lucky Lotto Numbers Are:‘ , nums )

imageSave then run the program – to see math results and random samples

image

image

All the math functions here return floating-point numbers of the float data type.

image

The list produced by random.sample() does not actually replace elements of the sequence but merely copies a sample, as its name says.

Calculating decimals

Python programs that attempt floating-point arithmetic can produce unexpected and inaccurate results because the floating-point numbers cannot accurately represent all decimal numbers.

image

inaccurate.py

imageStart a new program by initializing two variables with floating-point values

item = 0.70

rate = 1.05

imageNext, initialize two more variables by attempting floating-point arithmetic with the first two variables

tax = item * rate total = item + tax

imageNow, add statements to display variable values formatted to have two decimal places so trailing zeros are shown

print( ‘Item:\t’ , ‘%.2f’ % item )

print( ‘Tax:\t’ , ‘%.2f’ % tax )

print( ‘Total:\t’ , ‘%.2f’ % total )

imageSave then run the program – to see the output display an inaccurate addition total

image

image

expanded.py

imageTo help understand this problem edit all three print statements to display the variable values expanded to 20 decimal places, then run the modified program

print( ‘Item:\t’ , ‘%.20f’ % item )

print( ‘Tax:\t’ , ‘%.20f’ % tax )

print( ‘Total:\t’ , ‘%.20f’ % total )

image

image

Here, the variable values are formatted using a string substitution technique to show two decimal places – described in more detail here.

image

This problem is not unique to Python – Java has a BigDecimal class that overcomes this problem in much the same way as the decimal module in Python.

It is now clear that the tax value is represented numerically slightly below 0.735 so gets rounded down to 0.73. Conversely, the total value is represented numerically slightly above 1.435 so gets rounded up to 1.44, creating the apparent addition error.

Errors in floating-point arithmetic can be avoided using Python’s “decimal” module. This provides a Decimal() object with which floating-point numbers can be more accurately represented.

image

decimals.py

imageAdd a statement at the beginning of the program to import the “decimal” module to make all features available

from decimal import *

imageNext, edit the first two variable assignment to objects

item = Decimal( 0.70 )

rate = Decimal( 1.05 )

imageSave the changes then run the modified program to see both tax and total representations will now get rounded down – so the output will show accurate addition when string formatting is changed back to two decimal places

image

image

Always use the Decimal() object to calculate monetary values or anywhere that accuracy is essential.

Telling time

The Python “datetime” module can be imported into a program to make use of times and dates. It provides a datetime object with attributes of year, month, day, hour, minute, second, microsecond.

A datetime object has a today() function that assigns the current date and time values to its attributes and returns them in a tuple. It also has a getattr() function that requires two arguments specifying the datetime object name and attribute to retrieve. Alternatively, the attributes can be referenced using dot notation such as datetime.year.

image

As the datetime object is in a module of the same name, simply importing the module means it would be referenced as datetime.datetime. Use from datetime import * so it can be referenced just as datetime alone.

All values in a datetime object are stored as numeric values but can be usefully transformed into text equivalents using its strftime() function. This requires a single string argument that is a “directive” specifying which part of the tuple to return and in what format. The possible directives are listed in the table below:

Directive:

Returns:

%A

Full weekday name (%a for abbreviated day name)

%B

Full month name (%b for abbreviated month name)

%c

Date and time appropriate for locale

%d

Day of the month number 1-31

%f

Microsecond number 0-999999

%H

Hour number 0-23 (24-hour clock)

%I

Hour number 1-12 (12-hour clock)

%j

Day of the year number 0-366

%m

Month number 1-12

%M

Minute number 0-59

%p

AM or PM equivalent for locale

%S

Second number 0-59

%w

Week day number 0(Sunday)-6

%W

Week of the year number 0-53

%X

Time appropriate for locale (%x for appropriate date)

%Y

Year 0001-9999 (%y for year 00-99)

%z

Timezone offset from UTC as +HHMM or -HHMM

%Z

Timezone name

image

As the strftime() function requires a string argument, the directive must be enclosed between quote marks.

image

time.py

imageStart a new program by importing the “datetime” module to make its features available

from datetime import *

imageNext, create a datetime object with attributes assigned current date and time values then display its contents

today = datetime.today()

print( ‘Today Is:‘ , today )

imageAdd a loop to display each attribute value individually

for attr in \

[ ‘year’,‘month’,‘day’,‘hour’,‘minute’,’second’,’microsecond’ ] :

print( attr , ‘:\t’ , getattr( today , attr ) )

imageNow, add a statement to display time using dot notation

print( ‘ Time:‘ , today.hour , ‘:’ , today.minute , sep = ‘‘ )

imageThen, assign formatted day and month names to variables

day = today.strftime( ‘%A’ )

month = today.strftime( ‘%B’ )

imageFinally, add a statement to display the formatted date

print( ‘Date:‘ , day , month , today.day )

imageSave then run the program – to see the date and time values get displayed

image

image

Notice how the \ backslash character is used in this loop to allow a statement to continue on the next line without causing an error.

image

You can assign new values to attributes of a datetime object using its replace() function, such as today = today.replace(year=2015)

Running timers

Getting the current time both before and after an event means that the duration of the event can be calculated by their difference. The Python “time” module can be imported into a program to provide various time-related functions.

Current system time is usually counted as the number of seconds elapsed since the Epoch at 00:00:00 GMT on January 1, 1970. The time module’s time() function returns the current time in seconds since the Epoch as a floating point number when called.

image

The gmtime() function converts elapsed time from the Epoch to a struct_time object at UTC with the Daylight Saving Time always set to zero, whereas localtime() converts to a struct_time object at your local system time.

The figure returned by the time() function can be converted into a “struct_time” object using gmtime() or localtime() functions. This object has attributes of tm_year, tm_mon, tm_mday, tm_hour, tm_ min, tm_sec, tm_wday, tm_yday, tm_yday and tm_isdst that can be referenced using dot notation. For example, struct.tm_wday.

All values in a struct_time object are stored as numeric values but can be transformed into text equivalents using the strftime() function. This requires an argument that is a format “directive” followed by the name of the struct_time object. The possible directives include those listed in the tablehere for the datetime object. For example, strftime( ‘%A’ , struct ) for weekday.

Usefully, the time module also provides a sleep() function that can be used to pause execution of a program. Its argument specifies the amount of time in seconds by which to delay execution.

image

timer.py

imageStart a new program by importing the “time” module to make its features available

from time import *

imageNext, initialize a variable with a floating point number that is the current elapsed time since the epoch

start_timer = time()

imageNow, add a statement to create a struct_time object from the elapsed time value

struct = localtime( start_timer )

imageThen, announce that a countdown timer is about to begin from the current time starting point

print( ‘Starting Countdown At:’ , strftime( ‘%X’ , struct ) )

imageAdd a loop to initialize and print a counter variable value then decrement the counter by one and pause for one second on each iteration

i = 10

while i > -1 :

print( i )

i -= 1

sleep( 1 )

imageNext, initialize a variable with a floating point number that is the current elapsed time now since the Epoch

end_timer = time()

imageNow, initialize a variable with the rounded seconds value of the time difference between the two timed points

difference = round( end_timer - start_timer )

imageFinally, add a statement to display the time taken to execute the countdown loop

print( ‘\nRuntime:’ , difference , ‘Seconds’ )

imageSave then run the program – to see the loop pause on each iteration and elapsed time

image

image

The argument to the sleep() function may be a floating point number to indicate a more precise sleep pause time.

image

Do not confuse the time.strftime() function used in this example with the datetime.strftime() function used in the previous example.

Summary

•The sys module has attributes that contain the Python version number, interpreter location, and path to search for modules

•The keyword module has a kwlist attribute that contains a list of all current Python keywords

•The math module provides functions to perform mathematical procedures such as math.ceil() and math.floor()

•The math.pow() and math.sqrt() functions both return their results as a decimal value of the float data type

•Trigonometry can be performed using math module functions such as math.sin(), math.cosin() and math.tan()

•The random module provides a random() function that produces pseudo random numbers and a sample() function that produces a list of elements selected at random from a sequence

•Floating-point float numbers cannot accurately represent all decimal numbers

•The decimal module provides a Decimal() object with which floating-point numbers can be accurately represented to calculate monetary values

•The datetime module provides a datetime object with year, month, day, hour, minute, second, microsecond attributes that can be referenced by dot-suffixing or with the getattr() function

•A datetime object has a strftime() function that can specify a directive to return a formatted part of the object

•The time module provides a time() function that returns the current elapsed time in seconds since the Epoch

•The gmtime() and localtime() functions return a struct_time object with attributes containing date and time components