Reading Computer Science 1 CSci 1100 Lecture 3 Python Functions Most of this is covered late Chapter 2 in Practical Programming and Chapter 3 of Think Python. Chapter 6 of Think Python goes into more detail, but we are not quite ready for that yet. Back to Area and Volume Calculation Recall our program to compute the surface area and volume of a cylinder: >>> >>> radius = 2 >>> height = 10 >>> base_area = pi * radius ** 2 >>> volume = base_area * height >>> surface_area = 2 * base_area + 2 * pi * radius * height >>> print "volume is", volume, ", surface area is", surface_area volume is 125.6636, surface area is 150.79632 If we want to run all or part of this again, on different values, we either have to edit the program and rerun it, or we have to type the statements all over again. Instead, we will gather the code into one or more Python functions that we can run repeatedly. The purpose of today s class is to introduce the basics of writing and running Python functions. A Function to Compute the Area of a Circle In mathematics, you might write a function to calculate the area of a circle as a(r) = πr 2 In Python, when typing directly into the interpreter, we write >>> def area_circle(radius):...... return pi * radius ** 2 Then we can run this using >>> area_circle(1) >>> area_circle(2) >>> area_circle(75.1) Note that by using examples with small values for the radius we can easily check that our function is correct. Important syntax includes Use of the keyword def and the : to indicate the start of the function Indentation for the lines after the def line Blank line at the end of the function
The... are produced by the Python interpreter, just like the >>> are. What does Python do as we type? 1. Reads the keyword def and notes that a function is being defined 2. Reads the rest of the function definition, checking its syntax 3. Notes the end of the definition when the blank line is reached. 4. Sees the function call >>> area_circle(1) at what s known as the top level or main level of execution (indicated by the presence of >>>), and Jumps back up to the function Assigns 1 to radius Runs the code inside the function Returns the result of the calculation back to the top level and outputs the returned result 5. Repeats the process of running the function at the line >>> area_circle(2) this time with radius assigned the value 2 6. Repeats the process again at the line >>> area_circle(75.1) To reiterate, the flow of control of Python here involves Reading the function definition without executing Seeing a call to the function, jumping up to the start of the function and executing Returning back to the place in the program that called the function and continuing. Arguments, Parameters and Local Variables Arguments are the values 1, 2 and 75.1 in our above examples. These are each passed to the parameter called radius named in the function header. This parameter is used just like a variable in the function. The variable pi is a local variable to the function. Neither pi nor radius exists at the top / main level. At this level, they are undefined variables. Try it out. Exercise Write a function to convert the Celsius temperature to a Fahrenheit temperature. Write code to use the function. What are the arguments, parameters and local variables? 2
Functions with Multiple Arguments / Parameters For our volume calculation, we write a function involving two parameters, called with two arguments: >>> def volume(radius, height):...... return pi * radius ** 2 * height... >>> print "volume of cylinder with radius", 1, "and height 2 is", volume(1,2) >>> print "volume of cylinder with radius", 2, "and height 1 is", volume(2,1) Python determines which argument goes to which parameter based on the order of the arguments, the first going to radius and the second going to height. In this example, we have provided clearer, more extensive output. Python and Program Files Ways to run Python code include: Typing directly into the Python interpreter. This is what we do at the bottom of the Wing IDE. The >>> and... symbols are generated by the interpreter when we are typing in the program directly. Typing our code into a file (which we will call volume.py) and then either Opening the interpreter and running the code Running the Python code from a command shell The latter is in fact the most common way of running Python programs in practice. We will demonstrate all three in class. Note that providing more information in our print statement makes the output of the program from the command-line more self-explanatory. Functions That Call Functions Let s make use of our area of circle function to compute the surface area of the cylinder. Here is the Python code, in file surface_area.py: def area_cylinder(radius,height): circle_area = area_circle(radius) height_area = 2 * radius * pi * height return 2*circle_area + height_area def area_circle(radius): return pi * radius ** 2 print The area of a circle of radius 1 is, area_circle(1) r = 2 height = 10 print The surface area of a cylinder with radius, r print and height, height, is, area_cylinder(r,height) Now we ve defined two functions, one of which calls the other. 3
Flow of control proceeds in two different ways here: 1. Starting at the first print at the top level, into area_circle and back. 2. At the second print (a) into area_cylinder, (b) into area_circle, (c) back to area_cylinder, and (d) back to the top level. The Python interpreter keeps track of where it is working and where to return when it is done with a function, even if it is back into another function. Exercise Write a function to compute the area of a rectangle. Write a second function that takes the length, width and height of a rectangular solid and computes its surface area. Gathering Our Example Into One Big Function We can gather our code in one complete set of functions, writing them into a file called area_volume.py: def area_circle(radius): return pi * radius ** 2 def volume_cylinder(radius,height): area = area_circle(radius) return area * height def area_cylinder(radius,height): circle_area = area_circle(radius) height_area = 2 * radius * pi * height return 2*circle_area + height_area def area_and_volume(radius, height): print "For a cylinder with radius", radius, "and height", height print "The surface area is", area_cylinder(radius,height) print "The volume is", volume_cylinder(radius,height) Now we have functionality that we can use to generate clear, complete output for many different values of the radius of a circle and the base radius and height of a cylinder. Thinking About What You See Why is it NOT a mistake to use the same name, for example radius, in different functions (and sometimes at the top level). Let s Make Some Mistakes In order to check our understanding, we will play around with the code and make some mistakes on purpose Removing pi 4
Changing the name of a function Switching the order of the parameters in a function call Making an error in our calculation Why Functions? We write code that is Easier to think about and write Easier to test: we can check the correctness of area_circle before we test area_cylinder. Clearer for someone else to read Reusable in other programs Together these define the notion of encapsulation, another important idea in computer science! Python s Built-In Functions A few examples, some of which we have already seen abs pow int float round max min Let s play around to see what they do! Summary Functions for encapsulation and reuse Function syntax Arguments, parameters and local variables Flow of control, including functions that call other functions Built-in functions 5