Function Definition: Syntax and Semantics in Python

Unlike in the cases of if statements or for statements, a function definition does not involve the word “function.” As an example of a simple definition in Python, imagine a program that needs a function to print twenty # characters on a line. It could be defined as follows:

def pound20 ():

for i in range(0,20):

print (“#”, end=””)

The word def always begins the definition of a function. This is followed by the name of the function, in this case, pound20, because the function prints 20 pound characters (also known as a hash character or octothorpe). Then comes the list of parameters, which can be thought of as a tuple of variable names. In this case, the tuple is empty, meaning that nothing is passed to the function. Finally, we use the : character that defines a new suite that comprises the code belonging to the function. Now, the code is indented one more level, and when the indenta­tion reverts to the original level, the function definition is complete.

Calling this function is a matter of using its name as a statement or in an ex­pression, being careful to always include the tuple of the parameters. Even when the tuple is empty, it helps distinguish a function from a variable. A call to this function would be as follows:

The result is that 20 # characters are printed on one line of the output console.

A function can be given or pass one or more values that will determine the result of the function. A function cosine, for example, would be passed an angle, and that angle would be used to compute the cosine. Each call to cosine passing a different value can yield a different result. In the case of the function that prints pound characters it might be useful to pass it the number of pound characters to print. It should not be called pound20 anymore because it does not always print 20 characters. It is called poundn this time:

def poundn (ncharacters):

for i in range(0,ncharacters):

print (“#”, end=””)

The variable ncharacters that is given in parentheses after the function name is called a parameter or an argument, and indicates the name by which the func­tion refers to the value passed to it. This name is known only inside of the func­tion, and while it can be modified within the function, this modification does not have any bearing on anything outside. The call to poundn must now include a value to be passed to the function:

poundn (3)

When this call is performed, the code within poundn begins executing, and the value of ncharacters is 3, the value that was passed. It prints 3 characters and returns. A subsequent call to poundn could be passed a different number, perhaps 8, and then ncharacters would take on the value 8 and the function would print 8 characters. It will print as many characters as requested through the parameter

1. Problem: Use the function poundn to Draw a Histogram

In Chapter 2, a simple histogram was created from some print statements and loops. The same code was repeated many times, one for each histogram bar. As it happens, the character used to draw the histogram bars was the pound character, so the function poundn could be used as a basis for a histogram program. Here is the output that is desired:

Earnings for WidgetCorp for 2016 Dollars for each quarter

Q1: ########         190000

Q2: ################           340000

Q3: ##########################################        873000

Q4: ####################            439833

Each pound character represents $20,000, and there are four variables that hold the profit for each of the four quarters: q1, q2, q3, and q4. Given these criteria, a solution using poundn would call the function four times, once for each quarter:

print (“Earnings for WidgetCorp for 2016”)

print (” Dollars for each quarter “)

print (” ==============================”)

q1 = 190000    #  The dollar amounts for profits

q2 = 340000    #  in each of  the four quarters   of 2016

q3 = 873000

q4 = 439833

print (”Q1:   ”,  end=””)

poundn(int(q1/20000))   # Raw dollar amount is divided by

                             # 20000 to yield the number of

# characters. 

print  (”    ”,  q1)

print (”Q2:   ”,  end=””)

poundn (int(q2/20000)) print(“”,q2)

print (“Q3:   “,  end=””)

poundn (int(q3/20000)) print(“”,q3)

print (“Q4:   “,  end=””)

poundn (int(q4/20000)) print(“”,q4)

Each profit value must be scaled by dividing by 20,000, just as happened be­fore. In this case, the resulting value is passed to poundn, indicting the number of #s to draw.

2. Problem: Generalize the Histogram Code for Other Years

Any company will need to do financial reports every year at least. Hiring a programmer to do this task on a computer is not a reasonable thing to do, because computers can be made to do this job in a very general way. For example, given that each year will have four quarters and each quarter will have a profit, why not store these data as a list? Each year will have one list containing four items, and the name of the variable could initially be related to the year:

profit2016 = [190000, 340000, 873000, 439833]

The profit for the first quarter is profit2016[0], the second quarter is prof- it2016[1], and so on. Using this variable means passing one of the elements of the list to poundn instead of a simple variable, but that is fine, it’s a legal expression. So drawing the characters for the first quarter would be done with the following code:


Now consider what else gets printed. To print everything for the first quarter the code was:

print (“Q1: ”, end=””)


print (” “, q1)

This means that the label on the left, Q1, the parameters to poundn, and the actual value of the profit are needed. All of these are available and can be pro­vided within a simple loop. Assuming that the loop variable i runs from 0 to 3, the code within that loop that duplicates the previous example can be constructed one line at a time. In each iteration, the quarter is i+1 because i starts at 0; convert that to a string and build the label “Q1 :” from it:

print (Q1: “, end=””)

print (“Q”+str(i+1)+”: “, end=””)

This is probably the trickiest part. The label string is constructed from the letter “Q,” a number between 1 and 4 indicating the quarter, and for the terminal string “:” . These are simply concatenated together in the print statement.

Now call poundn as before:



Finally, print the raw dollar value on the right:

print (”         “, q1)

print (”         “, profit2016[i])

Using this plan, the entire histogram can be drawn using only four state­ments:

for i in range(0,4):

print (“Q”+str(i+1)+”: ”, end=””)


print (”  “, profit2016[i])

There is another step. Since this will be done every year, create a function that takes the data and the year as parameters. This function is called pqhisto- gram:

def pqhistogram (profit, year):

print (“Earnings for WidgetCorp for “+str(year))

print (” Dollars for each quarter “)

print (” ==============================”)

for i in range(0,4):

print (“Q”+str(i+1)+”:  “, end=””)


print (”  “, profit[i])

The function pqhistogram produces the same output as did the original pro­gram, and does so more generally and concisely. This function also brings to light two new ideas. One is that it is possible to pass more than one parameter to a function. The second is that it is possible to call a function from within another function; in this case, poundn is called from inside of pqhistogram. The call is made after defining the list that contains the profit values:

profit2016 = [190000, 340000, 873000, 439833]

pqhistogram (profit2016, 2016)

These parameters are positional; that is, the first value passed will corre­spond to the first name in the parameter list, and the second to the second. This is the default for functions with any number of parameters.


Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.

Leave a Reply

Your email address will not be published. Required fields are marked *