Lecture 4 — Using functions and modules¶
- Material for this lecture is drawn from Chapter 4 of Practical Programming.
- We will first concentrate on functions for different data types. Python already comes with many functions that we can use to solve lots of interesting problems.
- We will then talk about using existing modules, including the ones you write.
- We will revisit all these concepts in later lectures.
What have we learnt so far?¶
So far, we have learnt three basic data types: integer, float and strings.
We also learnt some valuable functions that convert between these data types (
str) and also those operate on strings.
>>> name = "Neil Degrasse Tyson" >>> len(name) 19 >>> (name+"! ")*3 'Neil Degrasse Tyson! Neil Degrasse Tyson! Neil Degrasse Tyson! ' >>> print "%s was a speaker in Commencement %d" %(name,2010) Neil Degrasse Tyson was a speaker in Commencement 2010
Python provides a number of functions that are already defined for you to use. These are called built-in functions.
We will see examples of these functions and experiment with their use in this class.
There are many other very interesting and useful string functions that will learn throughout the semester. Here are some first set of functions:
>>> name = "Neil Degrasse Tyson" >>> name.lower() 'neil degrasse tyson' >>> lowername = name.lower() >>> lowername.upper() 'NEIL DEGRASSE TYSON' >>> lowername.capitalize() 'Neil degrasse tyson' >>> lowername.title() 'Neil Degrasse Tyson' >>> "abracadabra".replace("br", "dr") 'adracadadra' >>> "abracadabra".replace("a", "") 'brcdbr' >>> "Neil Degrasse Tyson".find(" ") 4 >>> "Neil Degrasse Tyson".find("a") 9 >>> "Neil Degrasse Tyson".find("x") -1 >>> "Monty Python".count("o") 2 >>> "aaabbbfsassassaaaa".strip("a") 'bbbfsassass'
All these functions take one or more values, and return a new value. But they are called in different ways. We must learn how each function is called. We will see the reason for the differences later in the semester.
>>> episode = "Cheese Shop" >>> episode.lower() 'cheese shop' >>> len(episode) 11 >>> episode + "!" 'Cheese Shop!'
Be careful, none of these functions change the variable that they are applied to.
Exercise Set 1¶
Take a string in a variable called
nameand repeat each letters
nameas many times as
aappears in name (assume the word is all lower case).
>>> name = "amos eaton" ## your code goes here >>> name 'aamos eaaton'
Given a string in a variable called
name, switch all letters
e(only lowercase versions). Assume the variable contains only letters.
Hint: first replace each ‘a’ with ‘1’.
>>> name = "Rensselaer Polytechnic Institute" ## your code goes here >>> name 'Ranssalear Polytachnic Instituta'
Suppose you are given a string with only letters. Write a program that transforms the string into a hashtag.
'Things you wish you knew as a freshman'becomes
>>> word = 'Bring back the swarm' ## your code here >>> word ``'#BringBackTheSwarm'``
How about numerical functions¶
Many numerical functions also exist. Let us experiment with some of these first. Note what they do.
Let’s play around to see what they do!
Objects and Built_ins¶
All the functions we have seen so far are built-in to the core Python. It means that these functions are available when you start Python.
to see the full list.
All variables in Python are objects.
Objects are abstractions:
- They have a specific organization and structure to the data they store.
- They have operations/functions — we call them methods — applied to access and manipulate this data.
Often functions apply to a specific object type, like a string. We have seen these functions for strings. Their call takes the form:
>>> b = 'good morning' >>> b.find('o', 3)
It also works by:
>>> 'good morning'.find('o', 3)
You can see all the functions that apply to an object type with help as well. Try:
Modules are additional collection of functions and constants that provide additional power to Python programs.
Some modules come with Python, but are not loaded automatically. For example
Other modules need to be installed first. We installed a number of external modules for this class, such as
PILfor images. We will see the use of these modules later in the semester.
To use a function in a module, first you must load it into your program using
import. Let’s see the
>>> import math >>> math.sqrt(5) 2.2360679774997898 >>> math.trunc(4.5) 4 >>> math.ceil(4.5) 5.0 >>> math.log(1024,2) 10.0 >>> math.pi 3.1415926535897931
We can get an explanation of what functions and variables are provided in a module using the
>>> import math >>> help(math)
Exercise Set 2¶
Write a Python program that computes the area of a circle. Your program should use the math module. Remember, the formula is
What happens when we type
import math math.pi = 3
and then use
Different Ways of Importing¶
The way you import a module determines how you can use them in your program.
We can import only a selection of functions and variables:
>>> from math import sqrt,pi >>> pi 3.141592653589793 >>> sqrt(4) 2.0
Or we can give a new name to the module within our program:
>>> import math as m >>> m.pi 3.141592653589793 >>> m.sqrt(4) 2.0
Both of these methods helps us distinguish between the function
sqrtand the data
pidefined in the math module from a function with the same name (if we had one) in our program.
We can also do this (which is NOT recommended!):
>>> from math import *
Now, there is no name difference between the math module functions and ours. It is dangerous, better avoid it.
Now we have seen many different components of a program.
It makes sense to organize the program so that it is easy to see the flow of program
Follow the programming convention:
- a single comment explaining your program purpose,
- then, all variables and input commands
- then, all computation
- finally all output.
We will add more components to this program as time goes on.
In the rest of the class, we will first examine the following program structure and then write our own program to compute the the length of the hypotenuse of a triangle in the same format.
""" Author: CS-1 Staff Purpose: This program reads radius and height of a cylinder and outputs its area and volume. """ import math print "Computing area and volume of a cylinder" radius = float( raw_input("Enter radius ==> ") ) height = float( raw_input("Enter height ==> ") ) area = 2*math.pi*radius*height + 2*math.pi*radius**2 volume = math.pi*radius**2*height print "Area is: %.2f" %area print "Volume is: %.2f" %volume
Functions encapsulate a specific operation, which makes it possible to use them for more complex computation.
Also, once a function is written and tested, it can be used in many different programs and multiple times in the same program. This simplifies program logic.
Functions in modules can be used in many different program.
After they are imported, the functions in a module can be executed by a call of the form:
You can see the details of a function by:
Python has many modules that make it very easy to do many complicated tasks. If you do not believe it, try typing:
>>> import antigravity