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 modules, including modules that you write.
- We will revisit all these concepts in later lectures.
What have we learned so far?¶
So far, we have learned three basic data types: integer, float and strings.
- We also learned some valuable functions that operate on strings
len) and that convert between data types (
>>> 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
The functions that Python provides are called built-in functions.
We will see examples of these functions and experiment with their use in this class.
We will learn about many other interesting and useful string functions throughout the semester.
Here are a few more string 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¶
Write code that takes a string in a variable called
phraseand prints the string with all vowels removed.
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 and spaces.
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 and spaces. 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. You should make a note of 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:
- Each object defines an 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 collections 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. When we installed software in Lab 0, we installed a number of external modules, such as
PILfor images that we will use 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 what syntax you need to use the contents of the module 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. Since this leads to confusion when the same name appears in two different modules it is almost always avoided.
We have now seen several components of a program:
import, comments, and our own code, including input, computation and output statements. We will add more components, such as our own functions, as we proceed through the semester.
You should organize these components in your program files to make it easy to see the flow of program
We will use the following convention to order the program components:
- an initial comment explaining the purpose of the program,
- then all variables and input commands,
- then all computation,
- finally all output.
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
Python provides many functions that perform useful operations on strings, integers and floats.
Some of these functions are builtin while others are organized into modules
After a module is imported, the functions in the module can be used by a call of the form:
You can see the details of a function by:
Python has many modules that make it easy to do complicated tasks. If you do not believe it, try typing:
>>> import antigravity