Python training exercise 9

From BITS wiki
Jump to: navigation, search

Introduction

So now that we know how to make functions, how can you use them in another program if they're not inside the same file? In Python you can import a function into a file containing your code, even if the code for the function is in another file.

This is possible by using imports. In this way you can import your own functions, but also draw on a very extensive library of functions provided by Python that you can use to help you when you are writing a program. We will first look at the syntax for doing imports, then explore the most commonly used Python libraries.

Exercises

Import syntax

From within the same directory, you can import functions from other files. Make sure the first file we created that contains the getMeanValue() function is called 'functions1.py', then create a new file in the same directory with the following code:

from functions1 import getMeanValue
 
print(getMeanValue([1,4,5,4,3,45,5]))

So here we import the function getMeanValue (without brackets!) from the file functions1 (without .py extension!), then call it on a new list. However, when you run this program you will get output like this:

27.75
4916309.28571
9.57142857143

The last line is the one we were after, but where are the first lines coming from? When Python imports something from a file, it will also execute all other code that is in there (and not in a function). You can avoid this behaviour by always making sure that code is only executed if you directly call that file:

def getMeanValue(valueList):
 
  valueTotal = 0.0
 
  for value in valueList:
    valueTotal += value
 
  numberValues = len(valueList)
 
  return (valueTotal/numberValues)
 
if __name__ == '__main__':
 
  print(getMeanValue([4,6,77,3,67,54,6,5]))
  print(getMeanValue([3443,434,34343456,32434,34,34341,23])))
The line
if __name__ == '__main__':
will make sure that everything underneath it is only executed when you directly call the file, not when you import something from it.

Another way to use imports is not to import a specific function, but to import the whole 'file'. In this case you can call the function as a method, similar to the methods for lists and strings that we saw earlier:

import functions1
 
if __name__ == '__main__':
 
  print(functions1.getMeanValue([1,4,5,4,3,45,5]))


Python libraries import

Python has many ready-to-use functions that can save you a lot of time when writing code. The most common ones are time, sys, os/os.path and re.

With time you can get information on the current time and date, ...:

import time
 
if __name__ == '__main__':
 
  print(time.ctime())  # Print current day and time
  print(time.time())   # Print system clock time
  time.sleep(5)       # Sleep for 5 seconds - the program will wait here

See the Python documentation for a full description of time. Also see datetime, which is a module to deal with date/time manipulations.


sys gives you system-specific parameters and functions:

import sys
 
if __name__ == '__main__':
 
  print(sys.argv)        # A list of parameters that are given when calling this script 
                          # from the command line (e.g. ''python myScript a b c'')
  print(sys.platform)  # The platform the code is currently running on
  print(sys.path)      # The directories where Python will look for things to import
 
  sys.exit()          # Exit the code immediately

See the Python documentation for a full description.


os and os.path are very useful when dealing with files and directories:

import os
 
if __name__ == '__main__':
 
  # Get the current working directory (cwd)
  currentDir = os.getcwd()
  print(currentDir)
 
  # Get a list of the files in the current working directory    
  myFiles = os.listdir(currentDir)
  print(myFiles)
 
  # Create a directory, rename it, and remove it
  os.mkdir("myTempDir")
  os.rename("myTempDir","myNewTempDir")
  os.removedirs("myNewTempDir")
 
  # Create a the full path name to the first file of myFiles
  myFileFullPath = os.path.join(currentDir,myFiles[0])
  print(myFileFullPath)
 
  # Does this file exist?
  print(os.path.exists(myFileFullPath))
 
  # How big is the file?
  print(os.path.getsize(myFileFullPath))
 
  # Split the directory path from the file name
  (myDir,myFileName) = os.path.split(myFileFullPath)
  print(myDir, myFileName)

See the Python documentation for os and os.path for a full description.

A library that is very powerful for dealing with strings is re. It allows you to use regular expressions to examine text - using these is a course in itself, so just consider this simple example:

import re
 
if __name__ == '__main__':
 
  myText = """Call me Ishmael. Some years ago - never mind how long precisely -
having little or no money in my purse, and nothing particular to interest me on 
shore, I thought I would sail about a little and see the watery part of the 
world."""
 
  # Compile a regular expression, 
  myPattern = re.compile("(w\w+d)")  # Look for the first word that starts with a w,
                                     # is followed by 1 or more characters (\w+)
                                     # and ends in a d
 
  mySearch = myPattern.search(myText)
 
  # mySearch will be None if nothing was found
  if mySearch:
    print(mySearch.groups())

See the full Python reference on regular expressions for more information.

More exercises combining dictionaries, files and imports


Back to main page