Python-3.4.3/C4/Using-Python-Modules/English

From Script | Spoken-Tutorial
Revision as of 10:19, 8 October 2018 by Priyacst (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Title of script: Using Python Modules

Author: Puneeth, Aditya Palaparthy, Thirumalesh H S,Arun KP

Keywords: Python, Ipython, scripts, import, plot, modules, video tutorial


Visual Cue Narration
Show Slide

containing title

Welcome to the spoken tutorial on Using Python Modules.
Show Slide

Objectives


In this tutorial, you will learn to-
  • Execute python scripts from command line
  • Use import in scripts and
  • Import numpy and matplotlib.pyplot modules


Show Slide

System Specifications

To record this tutorial, I am using
  • Ubuntu Linux 16.04 operating system
  • Python 3.4.3
  • IPython 5.1.0 and
  • Gedit text editor


Show Slide

Prerequisite slide

To practise this tutorial, you should know how to
  • use plot interactively
  • embellish and save a plot

If not, see the relevant Python tutorials on this website.

Show Slide


What is a module?

First we will learn what is a module.


A module is a file containing Python definitions and statements.


Modules are used to break down large programs into small manageable and organized files.


Definitions from a module can be imported into other modules or to the main module.

Open text editor


Type, print ("Hello World")


Now let us see how to run a Python script from command line.


Open any text editor and type,

print inside brackets inside double quotes Hello World


We have created a simple python script to print hello world.

Save the script as hello.py Save this script as hello.py in the current working directory.
Open terminal and navigate to directory where hello.py was saved Now let us open the terminal.


Then navigate to the directory where hello.py is saved.

Type,

python3 hello.py

Now type, python3 hello.py and press Enter.


It executes the script and gives the output as Hello World.


From here onwards, remember to press the Enter key after typing every command on the terminal.

Open the four_plot.py file in text editor and show Next we will see how to import modules and use them in python scripts.


Let me open the file four underscore plot.py in the text editor.


This file is available in the Code files link of this tutorial.


You can download and use it.

Highlight the 4 plot command This code will plot for x, -x, sin of x and xsin of x
Show slide

Four plot Problem

When we run this code, we will see the final plot as shown here.
Type,

python3 four_plot.py

Now let us run the file four underscore plot.py as a python script.


Type,

python3 four underscore plot.py


It gives an error linspace() is not defined.


It means that,

function linspace() is not available in the current namespace.


A namespace is a system for making all the names in a program to be unique.

Switch to four_plot.py Let us go back to the file four underscore plot.py.
Add the line as first line in four_plot.py and save


from numpy import *

Highlight linspace

Add this line as the first line in the script,


from numpy import asterisk


When we use asterisk in imports, all the functions and constants are imported from numpy module.


linspace is a function available in numpy.

Save the file Press Ctrl + S to save the file.
Type,

python3 four_plot.py

Now let us run the script again,


Now it gave another NameError: nameplot’ is not defined.

Open four_plot.py in text editor Let us edit the four underscore plot.py file again.


Add the following as the second line in our script.

from matplotlib.pyplot import *


plot is a function which is available in the matplotlib.pyplot.

Save the file Now save the file.
python3 four_plot.py


We will run the script.


We get the output now.


We imported all the required modules using the keyword import.

Close the window Let me close the window.
Show Slide

Import functions


We can import only functions which are required from a module as,


from numpy import linspace, pi, sin

instead of,

from numpy import *


In the same way we can import only required functions from matplotlib.pyplot

instead of,

from matplotlib.pyplot import *

slide :

Import Functions

* It is always good to use function names instead of asterisk.
  • If we use asterisk to import from a particular module, all the functions will be imported.
  • It replaces some existing functions with the same name in the namespace.


Switch to script 'four_plot.py'


delete the first two lines and add the following


from numpy import linspace, pi, sin


from matplotlib.pyplot import plot, legend, annotate


from matplotlib.pyplot import xlim, ylim, title, show

Now we will add only required functions from numpy and matplotlib.pyplot



Save the file Let us save the file.
python3 four_plot.py We will run the code again in the terminal.


Here, we got the plots for x,-x,sin of x and xsin of x in a single figure.


In this method we imported the required functions to the current namespace.

There is another way of fixing errors.


Let us see that.

Highlight import matplotlib.pyplot as plt


Highlight

numpy.pi in line 3 and line 10, 11


plt.plot in line 4

plt.legend in line 8

plt.annotate in line 9

plt.xlim, plt.ylim in line 10 and 11

plt.show() in line 12


Open the file another underscore fix.py


This file is also available in the code files link of this tutorial.


Notice that we are going to use the name plt instead of matplotlib.pyplot.


plt is used as alias to the module matplotlib.pyplot


Now, we use numpy.pi instead of just pi as we did in four underscore plot.py.


Plot functions are called as

plt.plot()

plt.legend()

plt.annotate()

plt.xlim

plt.ylim

plt.show()


The advantage is that function names in imported modules do not get added to the current namespace.


In order to use a function in an imported module, we need to mention module-name.function-name

Show Slide


Exercise 1

Pause the video here.


Try this exercise and then resume the video.


Write a python script to plot a sine wave from -2pi to 2pi.

show text for codefiles


Open sine.py and show it

Open the file sine.py for the solution.


This file is also available in the code files link.


In the first line we import the required functions.


The functions linspace, sin and constant pi are imported from the module numpy.


We import the functions plot, legend, show, title, xlabel and ylabel from matplotlib.pyplot.


And the rest of the code is to generate the plot.

Type,

python3 sine.py

Let us run the code and see the output.


In the terminal, type


python3 sine.py


Now we can see our sine plot.


Close the terminal.


Let us move further in our topic.

Type,

ipython3

We can run Python scripts in IPython interpreter also.


Open another terminal and start the ipython interpreter by typing


ipython3

Type,

%run four_plot.py

Navigate to the directory where four underscore plot.py is saved and type


percentage run four underscore plot.py


As before we can see the output with 4 plots.

Show Slide

Python standard library

Python has a very rich standard library of modules.


Some of the standard modules are,

  • for Math: math, random
  • for Internet access: urllib2, smtplib
  • for System and Command line arguments: sys


Show Slide

Python standard library

Few more libraries
  • for Operating system interface: os
  • for regular expression: re
  • for compression: gzip, zipfile, tarfile

For more information refer to the below link.

Show Slide

Summary


This brings us to the end of this tutorial. Let us summarize.

In this tutorial, we have learnt to,


  • Run scripts from command line
  • Import modules by specifying the module name followed by an asterisk
  • Import only the required functions from modules by specifying the function name
  • Use python standard library.


Show Slide


Evaluation


Here are some self assessment questions for you to solve
  1. Which among the below is the most correct?
  2. How the functions xlim() and ylim() can be imported to the current namespace?


Show Slide


Solutions


And the answers,
  1. The option from matplotlib.pyplot import plot is the most correct one. Because plot is a function of matplotlib.pyplot module.
  2. Functions xlim() and ylim() can be imported to the current namespace as, from matplotlib.pyplot import xlim, ylim


Show Slide Forum Please post your timed queries in this forum.
Show Slide Fossee Forum Please post your general queries on Python in this forum.
Slide Textbook Companion FOSSEE team coordinates the TBC project.
Show Slide Acknowledgment


Spoken Tutorial Project is funded by NMEICT, MHRD, Govt. of India.

For more details, visit this website.

Previous slide This is Priya from IIT Bombay signing off.

Thanks for watching.

Contributors and Content Editors

Nancyvarkey, Nirmala Venkat, Priyacst