Jason M. Grant

Assistant Professor of Computer Science


Functions without Input or Output

Functions are often thought of as “boxes” that take some data as input and return some sort of output. A function is not required to have either an input or an output. Let’s start with a few basic examples.

In mathematics, the equation for a line can be written in the form of y = ax+b. We can also refer to y as a function of x. Therefore, we can rewrite the same equation as f(x)=ax+b, where  is our function and  is the input. Let’s assign the value of 2 to a and 5 to b. Now, f(x)=2*a+b . This produces the following graph.

A function in Python can be defined very similarly. If we name our function f, then the function can be declared as such:

def f(x):
    return 2 * x + 5

Notice the format of the function in Python. Each function begins with def, followed by the name of the function, its arguments (input), and a colon. Lastly, the function returns the output with using the keyword return followed by the value it is returning.

Below is an example of a function that does not have a input nor does it return an output, but inside the function it makes several print statements to the user, another method of output which we have see before.

Calculating the Area of a Circle

Let’s look at another example of a function, which calculates the area of a circle. Based upon our knowledge from geometry, we use the formula

LaTeX: a\:=\:\pi\cdot r^2

to calculate the area. Thus, for any radius , we can calculate the area since  is a constant. One way for us to write this function would be to define  for a given number of significant digits.

pi = 3.141592654

Another way would be to import a module that already defines the value of pi. Notice line 1 of the program that imports the math module. Next, in line 6, the value of pi is obtained by calling math.pi.

Calculating the Volume of a Circle

In this section, we compute the volume of a cone using two approaches. One approach would be to calculate the volume using the same methodology from the area of a circle function. The formula for the volume of a cone can be expressed as 

LaTeX: v\:=\:\frac{1}{3}\pi r^2h

. Now, we have two input variables. To create a function in Python with two input variables, we define the function as such:

def functionName( var1, var2):

The function for the volume of a cone can be found on line 8. Another way to define the volume of a cone would be to do so in terms of the area of the base circle. Since, we already have a formula for the area of a circle, we could use this function in our new function definition for the volume of a cone. Notice that both lines 18 and 19 print the same value.

Calculating Overtime

This example calculates base pay plus additional pay for overtime work, based upon a 40 hour work week. In this function, we introduce the if/else statement as well. We will explore conditional statements in more detail in one week.