Difference between revisions of "Python-3.4.3/C4/Writing-Python-Scripts/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
 
Line 322: Line 322:
 
| style="background-color:#ffffff;border:0.5pt solid #000001;padding-top:0cm;padding-bottom:0cm;padding-left:0.097cm;padding-right:0.191cm;"| Now we will check the changes by '''importing''' the '''module'''.
 
| style="background-color:#ffffff;border:0.5pt solid #000001;padding-top:0cm;padding-bottom:0cm;padding-left:0.097cm;padding-right:0.191cm;"| Now we will check the changes by '''importing''' the '''module'''.
  
 +
Type,'''import gcd_script'''
  
 
We didn’t see any changes.
 
We didn’t see any changes.

Latest revision as of 13:08, 24 October 2018

Title of script: Writing Python scripts

Author: Aditya Palaparthy, Arun KP

Keywords: Python, Ipython, python script, import module, name variable, video tutorial


Visual Cue
Narration
Show Slide title Welcome to the spoken tutorial on Writing Python scripts.
Show Slide

Objectives


In this tutorial we will learn,
  • What is importing
  • Write your own Python modules and
  • Understand the double underscore name double underscore double equal to within double quotes double underscore main double underscore idiom
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
  • Run basic Python commands on the IPython console and
  • Use Python modules.

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

Show Slide

Python Modules


We can write Python modules to bundle functions.


We can then make use of these functions by importing modules to other scripts.

Let us first write a function and save it in a script.
Open an editor and type the following code

def gcd(a, b):

while b:

a, b = b, a%b

return a

if gcd(40, 12) == 4:

print ("Everything is OK")

else:

print ("The GCD function is wrong")

Open any text editor and type the below code.



Highlight def gcd(a, b):

while b:

a, b = b, a%b

return a


Highlight if gcd(40, 12) == 4:

print ("Everything is OK")

else:

print ("The GCD function is wrong")

This Python module has a function to compute gcd of two numbers.


Please take care of the indentation.


We have included a test case in the script.


This test case will check the gcd function every time the script is run.

Save the script as gcd_script.py


Let us save the file as gcd underscore script.py in the current working directory.
Type

ipython3

Open a new terminal.


Type,

ipython3 and press Enter.


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

%run gcd_script.py


Highlight the output

Everything is OK

Now we will run the script.


Type,

percentage run gcd underscore script.py


We get an output which says “Everything is OK”.

Switch to the gcd_script.py It means that the test case checking gcd inside brackets 40 comma 12 equals to 4 is passed.


What if we want to use the gcd function in some other scripts?


This is possible since every Python file can be used as a module.

Type,

import sys


But first, we will understand what happens when we import a module.


Type,

import sys

Type, sys.path Now type sys.path
Highlight the output


Highlight the empty string


We can see a list of locations.


This indicates that Python searches for a module when it encounters an import statement.


The standard modules are built into Python itself.


Otherwise it is found in system locations like slash usr slash lib slash python3.4 slash


The first item in the list is an empty string.


It means the current working directory is also searched.

Type,

import gcd_script


Highlight Everything is OK


Type,

print("gcd of 187 and 391 is", gcd_script.gcd(187, 391))


Highlight gcd of 187 and 391 is 17

We can import a module present in the current working directory.


Type,

import gcd underscore script


Since gcd underscore script.py is in the current working directory, import will work directly.


Type the print statement as shown here.


We get the gcd of 187 and 391 as output, which is 17.

Highlight Everything is OK


We can also see the output “Everything is OK” that we added as test code.


This is also executed when we imported gcd underscore script.


The test code is added to check the gcd function.

Slide:

__name__ variable.


Highlight __name__

Test code should only be executed when we run the Python script independently.


To execute the test code when the module is imported to other scripts, we can use double underscore name double underscore variable.


Hereafter I will call this as name variable.

Switch to gcd_script.py


Add if __name__ == "__main__":

after the line return a

First, we shall look at how to use the variable and then understand how it works.


Now we will add this variable in the script gcd underscore script.py


Type the following after return a statement

if double underscore name double underscore double equal to inside double quotes double underscore main double underscore colon


Indent the code properly.

Save the file Save the file.
Type

%run gcd_script.py


Highlight

Everything is OK

Let us run the code.


Type,

percentage run gcd underscore script.py


We can see that the test is executed successfully and we get output as Everything is OK

Type, import gcd_script


Type,

exit

Now we will check the changes by importing the module.

Type,import gcd_script

We didn’t see any changes.


Note that, once a module is imported, it cannot be imported again in an existing IPython console.


So we will exit the existing IPython console by typing exit.

Open terminal and type ipython3 Open another terminal. Type ipython3.
Type

import gcd_script

Now we will import gcd underscore script.py.


Type,

import gcd underscore script


We can see that now the test code is not executed.


Everything is OK is not displayed as output.

Open gcd_script.py and highlight the if __name__ == "__main__":


block in the file gcd_script.py

The name variable is local to every module.


It is equal to main only when the file is run as a script.


Hence, all the code under the block, if name double equal to within double quotes main is executed only when the file is run as a Python script.

Switch terminal Switch back to the terminal.
Type,

from gcd_script import gcd


def check_relative_prime(a,b):

if gcd(a,b)==1:

print("Yes, %d and %d are relatively prime" %(a,b))

else:

print("No, %d and %d are not relatively prime" %(a,b))


check_relative_prime(11,3)


Highlight Yes, 11 and 3 are relatively prime

Type the following code which checks whether two numbers are relatively prime.


We have imported gcd function from gcd underscore script.


And use it in our calculations without the test code being executed.


Two numbers are relatively prime when their gcd is equal to one.


So we get output as Yes, 11 and 3 are relatively prime.

Slide Every Python file can be run in two ways:
  • As an independent stand-alone script or
  • As a Python module which can be imported by other Python scripts or modules.
Show Slide

Summary slide


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


In this tutorial, we have learnt to,

  • Import a module
  • Use a script as a module
  • Write test condition using the name variable
  • Restart IPython3 if a changed module is to be imported again.
Show Slide

Evaluation

Here are some self assessment questions for you to solve
  1. Which of the following variables contains the locations to search for Python modules
  2. A module should contain only one function. True or False
Show Slide


Solutions

And the answers.
  1. sys.path contains the locations to search for Python modules.
  2. False. A module can contain a wide range of functions.
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

Acknowledgement

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

For more details, visit this website.

Show Slide Thank You This is Priya from IIT Bombay signing off. Thanks for watching.

Contributors and Content Editors

Nancyvarkey, Nirmala Venkat, Priyacst