Lecture Notes on Functions 1 Introduction

advertisement
Lecture Notes on
Functions
15-112: Introduction to Programming and Computer Science
Saquib Razak
Lecture 1
August 25, 2013
1
Introduction
You have learnt that computer programs are used to solve problems. To get us started on how to program
computers, we have already learnt the concept of variables, expressions, getting input from the user and
printing messages to the screen. In this lecture, we will learn the concept of a function. Solving a problem
often requires you to perform several small, well-defined, and self contained tasks in a specific sequence.
Functions are a way of organizing your code in smaller units that perform a single task. Let’s work
through an example to make this clear.
We would like to write a program that reads a radius of a circle from the user and then prints some
properties like diameter, area, and circumference of this circle. Here is how we will solve this problem:
• Print a welcome message for the user
• Read the radius of a circle from the user
• Print properties of the circle
So we can see that we can solve this problem by accomplishing three tasks in order. Lets analyze the
first task:
Print a welcome message for the user. This is simple task that might not be necessary but nonetheless
useful as it gives the user an idea of what this program will do. To do this task we will write a function
that prints a few lines of infomation - we will call this function greetUser.
def greetUser ( ) :
print "Hello User: Welcome!!"
print "This program is written by Saquib Razak"
print "I will ask you to enter radius of a circle."
print "Then I will print the diameter, area, and cicumference of this circle"
L ECTURE N OTES
A UGUST 25, 2013
Functions
L1.2
We can use this function in our code by ”calling” or ”invoking” the function as follows:
greetUser ( )
The overall program would look as follows:
def greetUser ( ) :
print "Hello User: Welcome!!"
print "This program is written by Saquib Razak"
print "I will ask you to enter radius of a circle."
print "Then I will print the diameter, area, and cicumference of this circle"
greetUser ( )
Lets look at the structure of the above program. Python starts executing its code from the first line
that has no spaces on the left of the line (the first line that is not indented) and does not start with the
word ”def”. So in the above example, greetUser ( ) is the first line that is not indented so the program will
start from there. Whenever you have a name followed by paranthesis ”( )”, you are invoking a function.
Invoking a function means that you are asking python to run the function called greetUser. The python
environment then starts looking for a function called greetUser.
A function is defined by using the keyword ”def” followed by the name of the function followed by
a colon ”:”. In the above code, the first line defines a function called greetUser. All lines following the
function name that are indented are part of the function. We see that the following four print statements
are indented so they form the body of the function ”greetUser”. Once a function is invoked, python will
start executing from the first line of the function body and will continue sequentially until the last line
of the function. Once the last line of function body is executed, program execution will return to the
statement that originally invoked the function.
If we save the above code in a file and run it , we will see the following output on the screen:
Hello User: Welcome!!
This program is written by Saquib Razak
I will ask you to enter radius of a circle.
Then I will print the diameter, area, and cicumference of this circle
2
Functions with Return Values
Lets revisit our algorithm for this simple program:
• Print a welcome message for the user
L ECTURE N OTES
A UGUST 25, 2013
Functions
L1.3
• Read the radius of a circle from the user
• Print properties of the circle
We still need to finish the second and third tasks. Let’s look at the second task. We need to ask the
user for a radius: we will write a function that will do that for us. What we need to make sure is that
once the function takes the user’s input, it should give that value back to the main program. The main
program should save this value returned by the function. Lets see how we define this function, we will
call this function getRadius:
def getRadius( ) :
# read the input as a string
inp = raw_input("Enter the radius of the circle")
#convert the string into a floating point number
r = float(inp)
return r;
The last statement in this function returns the value stored in the variable r to the main program. Whenever a function needs to send a value back to the main program, it uses the keyword ”return” followed
by the value.
Just like in the example of getUser, we will call the getRadius function by using its name followed by
the parenthesis. The difference in calling the getRadius function is that we need to store the value given
to us by the function. In the following code, we call the getRadius function and save the value returned
by it in a variable called rad by using the assignment ”=” operator.
rad = getRadius( )
The complete code that we have developed so far looks as follows:
def getRadius( ) :
# read the input as a string
inp = raw_input("Enter the radius of the circle")
#convert the string into a floating point number
r = float(inp)
return r;
def greetUser ( ) :
print "Hello User: Welcome!!"
print "This program is written by Saquib Razak"
print "I will ask you to enter radius of a circle."
print "Then I will print the diameter, area, and cicumference of this circle"
L ECTURE N OTES
A UGUST 25, 2013
Functions
L1.4
greetUser ( )
rad = getRadius( )
Remember that execution of python programs start from the first line that is not indented. In this case,
our program first calls the greetUser function to print a welcome message and then calls the getRadius
function to read the radius of the circle from the user and then save the value in a variable called ”rad”.
3
Functions with Input Parameters
The next step in our nifty little program is to print diameter, area, and circumference of the circle. We can
do this in either three separate functions or within the same function. Often the choice of how to divide
your program will depend on your experience and expertise. Functions, in general, should do a single
complete task within an algorithm.
Let’s write one function that will print all three properties of the circle. We will call this function
printCircleProperties. It is a good idea to name functions in a way that reader can understand what the
function does by looking at its name. This function will need to know the radius before it can find the
properties of the circle. It is possible to pass values to a function that it needs. In the context of the function, these values are called the ”input parameters” of the function. Let’s write the printCircleProperties
function with one input parameter. If a function needs more than one parameters, the names of these
parameters are separated by commas.
def printCircleParameters ( radius ):
print "Diameter of the circle is ", radius * 2
print "Area of the circle is ", (22.0/7) * radius * radius
print "Circumference of the circle is", 2 * (22.0/7) * radius
Notice that here, radius is a variable that is an input parameter for this function. For the printCircleParameters function to work, the code that will call this function will need to pass in the value for ”radius”.
The follow code calls the printCircleProperties with a value of 4.5 for radius.
printCircleProperties( 4.5)
The complete code for our example problem is shown below where we call the printCircleProperties
function with the radius entered by the user.
# This function asks the user to enter a radius and passes the value entered by
# the user back to the calling program as a floating point number
def getRadius( ) :
L ECTURE N OTES
A UGUST 25, 2013
Functions
L1.5
# read the input as a string
inp = raw_input("Enter the radius of the circle")
#convert the string into a floating point number
r = float(inp)
return r;
# This function prints the following properties of a circle
#
- Diameter
#
- Area
#
- Circumference
# The function needs radius of the circle as input parameter
def printCircleParameters ( radius ):
print "Diameter of the circle is ", radius * 2
print "Area of the circle is ", (22.0/7) * radius * radius
print "Circumference of the circle is", 2 * (22.0/7) * radius
# This function prints a welcome message and explains what this program does
def greetUser ( ) :
print "Hello User: Welcome!!"
print "This program is written by Saquib Razak"
print "I will ask you to enter radius of a circle."
print "Then I will print the diameter, area, and cicumference of this circle"
# our algorthm consists of the following steps:
# - Print a welcome message for the user
# - Read the radius of a circle from the user
# - Print properties of the circle
greetUser ( )
rad = getRadius( )
printCircleProperties( rad)
L ECTURE N OTES
A UGUST 25, 2013
Download