10.1 Modules

You have seen how you can reuse code in your program by defining functions. What if you wanted to reuse a number of functions in other programs that you write? The answer is modules.

Modules are Python's solution to manage code, putting code that are somewhat related into separate groupings for easy management. These code groupings are called modules, libraries contain commonly used modules for generic needs.

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. A very simple module can be a a file with a .py extension that contains functions and variables. (Now it's time to understand why all previous programs we named them sth.py)

The functions, variables in a module are called attributes of a module.

In order to use the module, (i.e. use the functions or variables in it), we need to tell Python to get that file and read it into the current application. We import that file by specifying import modName, then access the attributes in that module with the ' . ' (dot operator), providing the module name and the attributes' name joined together with a “dot” like: modName.itemName. You can think of this as lastname.firstname where the lastname is the module family and the firstname is the individual entry in the module.

We use the same dot notation to access members of the module as mansioned before with string and lists methods. Python makes good reuse of the same notation to give the distinctive 'Pythonic' feel to it so that we don't have to keep learning new ways to do things. Keep this in mind as we go on to classes and objects.

A good example speaks a thousand words:

Let's make a simple module hello.py and include function say_hello() and two variables: morning, evening in it.

Ex. 10.1-1 hello.py

# hello.py

def say_greeting(name):
    print( 'Hello, ', name )

morning = 'Good morning!'
evening = 'Good evening!'

Now, we start another file, use_hello.py, we will see how to use hello.py in the new separate application.

Ex. 10.1-2 use_hello.py

# use_hello.py

import hello

hello.say_greeting('Sniffy')
hello.morning

# run...
Hello, Sniffy
Good morning!

Another example:

Ex. 10.1-3 farm.py Now I have a module named farm.py, I put a function in it called sing(), and two variables in it named cow and duck, like this:

# farm.py

def sing( ):
    print ('Old MacDonald had a farm E-I-E-I-O' )

cow = 'Moo Moo Moo'
duck = 'Quack Quack Quack'

Now I can use that module with import keyword with the module name (farm) and access the sing() function and the variable duck using the dot notation as: farm.sing() farm.duck

Ex. 10.1-4 import_farm1.py

# import_farm1.py

import farm

farm.sing( )
print()
print (farm.duck)
print (farm.cow)

# run ...
Old MacDonald had a farm E-I-E-I-O

Quack Quack Quack
Moo Moo Moo

Other than import the whole module, we can import some particular items using from modName import itemName. To get access to the attributes we can directly call the item names.

Ex. 10.1-5 import_farm2.py

# import_farm2.py

from farm import sing, cow, duck

sing()
print()
print (duck)
print (cow)

# run...
Old MacDonald had a farm E-I-E-I-O

Quack Quack Quack
Moo Moo Moo

Whenever you see import in a program, you know the programer is bringing in code from elsewhere. Below are different ways to import a module:

  • import module
  • from module import class/function
  • from module import *

Note: The last line will import everything from particular module. Although it might save you some typing, but it can make debugging your code difficult. It's better to just import the specific class or function you need, or import the whole module using the first and second lines.

==??

import fruit
import fruit as f
from fruit import fruit_prices
from my_package.fruit import fruit_prices

It is strongly recommended to list the imported variables and functions explicitly instead of using the import syntax. This makes debugging a lot easier. WARNING: In general, avoid using the from..import statement, use the import statement instead. This is because your program will avoid name clashes and will be more readable. You could also use: from mymodule import But WARNING: Remember that you should avoid using import-star, i.e. from mymodule import *.

8.2 Math Module

There are many modules that come with Python as part of the standard library.

The Python Documentation site for Python version 3 is an extremely useful reference for all aspects of Python. The site contains a listing of all the standard modules that are available with Python.

https://docs.python.org/3

The math module contains the kinds of mathematical functions you would typically find on your calculator and some mathematical constants like pi and e.

Ex. 8.2-1 pi_math.py

# pi_math.py
# use pi in math module

import math    

def area(radius):
    return (math.pi) * radius**2

print(math.pi)
print(area(10)    

# run...
3.141592653589793
314.1592653589793

Some commonly used functions in math module:

Ex. 8.2-2 funs_math.py

# some functions in math module

>>>import math

>>>print( math.factorial(3) )   # Remember we made a function to calculate factorial? Haha, acturally there is no need.
6
>>>print(math.sqrt(100))   # returns square root of x
10
>>>print(math.pow(2,3))    # 2 to the power of 3
8.0
>>>
>>># sin(90): 90 converted to radians and then calculate it's sin() value

>>>print(math.sin(math.radians(90))) 
1.0

8.3 Random Module

random(), randint(), randrange(start, stop, step), choice()

The random module is included as part of Python's standard library. It is very useful for generating random numbers.

We can use the randint(start, stop) function to get random integers between the lower end and the upper end(the upper end is not included). Let's import the random module and get access to the randint() function.

Ex. 8.3-1 randint.py

# use randint() in random module

>>>import random
>>>random.randint (0, 100)
18
>>>random.randint (0, 100)
59

Or we can also choose to import just what we need by using the from module import class/function syntax, so we can avoid typing random. many times.

Ex. 8.3-2 randint2.py

# another way to access randint() 

>>> from random import randint       
>>> for i in range (5):     # to generate 5 random integers
        print( randint (0, 100) )
...#run
34
26
98
10
58
>>>

Choice( ) is another very useful function in random module. It takes a list or tuple and randomly returns one item in it.

Ex. 8.3-3 choice.py

# choice.py
# get a random item from a list of fruits
>>> from random import choice
>>> fruits = ['apple', 'pear', 'orange', 'kiwi']
>>> choice(fruits)
'orange'
>>> choice(fruits)
'apple'
>>>

Other functions in random module: random() function returns a floating point number in the range [0.0, 1.0)

0.0 is possible, but all returned numbers will be strictly less than 1.0

randrange(start, stop, step) function generates an integer between its lower and upper argument, using the same semantics as range(start, stop, step)

randrange(0,10,2) returns one integer from 0,2,4,6,8

++++++ ?????? end chapter here??

8.4 datetime Module

Using the datetime module

time, a class in datetime module datetime The datetime module contains datetime objects, which can be used to hold both a date and a time. instances?

results matching ""

    No results matching ""