Module 0.3 - Simple Functions

Objectives

By the end of this module, for simple Hello World-like programs, you will be able to:

  • Demonstrate function calls.
  • Use mental tracing to identify output without execution.
  • Add numbered comments to show an execution trace.
  • Identify and correct syntax errors related to the above objectives.

0.3.0 - An Example With Function Calls

Consider a program that generates a simple report:

print("Today's weather forecast for Washington, DC is:")
print(" - High temperature of 84 degrees")
print(" - Low temperature of 71 degrees")
print(" - 25% chance of rain")
  • While this example is simplified, computers are very commonly used to write ‘reports’ such as this
  • Ths is the basis for many websites that automatically generate content (think of a social media feed) that is different for each individual user

It is useful for us to be able to re-use this code and run it more than once. To write the same report twice, we could write out the code twice:

print("Today's weather forecast for Washington, DC is:")
print(" - High temperature of 84 degrees")
print(" - Low temperature of 71 degrees")
print(" - 25% chance of rain")

print("Today's weather forecast for Washington, DC is:")
print(" - High temperature of 84 degrees")
print(" - Low temperature of 71 degrees")
print(" - 25% chance of rain")

However, Python gives us a more efficient - easier to write way. We define a function that performs the individual task, in this case, a function that writes the report.

def weather_report():
  print("Today's weather forecast for Washington, DC is:")
  print(" - High temperature of 84 degrees")
  print(" - Low temperature of 71 degrees")
  print(" - 25% chance of rain")

weather_report()
  • Let’s start by distinguishing between a function definition (which uses def and merely tells Python what the function is about), and invocation (which asks Python to execute the function at that moment).
  • A function definition is a piece of code that begins with the word def. A function definition is sometimes also called function declaration .
  • A function definition does not execute the code immediately.
  • Instead it’s like saving in one place a bunch of instructions that can be invoked with just the name of the function.
  • This saves writing lots of code if a group of code can be given a name (in this case, a function name). A function definition has 5 elements:

  • The keyword def
  • A unique function name, in this case, weather_report
  • Parentheses after the function name
  • A colon after the parentheses
  • An indented block of code after the colon

Exercise 0.3.1

Exercise 0.3.1

Type up the above in weather_function.py and run it.

  • Code inside the indented “block” is included in the function.
  • The indented block continues for as long as lines of code are indented.
  • Line 7 of the program above is outside of the function definition: it is the function “invocation,” or function “call.”
    • Writing the function name followed by parentheses indicates that the code in the function should run.
    • The function is defined once, but can be used any number of times.
    • For now, we haven’t put anything inside of the parentheses. We will see later how the inside of the parentheses can be used.

Exercise 0.3.2

Exercise 0.3.2

Modify the program to add two more function calls to the weather_report() function (a total of three). When you run the program, you should see the report print out three times.

  • Function definitions also help isolate code so that one doesn’t have to see or understand what’s inside to use it. We’ve already used such a function before: the print function. The print function is defined internal to Python.
  • We don’t type its definition, nor do we see its definition.
  • We can use it without defining it, because it is “built in” to the Python programming language.
Indentation:

Pay careful attention to indentation. The line that begins with def should not be indented. Other lines that belong to the function should be indented. There are other forms of indentation that we’ll point out as we proceed - they’re all important.


We will now modify the report generator to use several functions. Pay careful attention to the order in which functions are defined and the order in which functions are called.

def preamble():
  print("Today's weather forecast for Washington, DC is:")
  
def precipitation():
  print(" - 25% chance of rain")

def temperatures():
  print(" - High temperature of 84 degrees")
  print(" - Low temperature of 71 degrees")

preamble()
temperatures()
precipitation()
  • temperatures() is defined after precipitation()
  • temperatures() is called before precipitation()

Exercise 0.3.3

Exercise 0.3.3

Write the above program as function_order.py. Run the program to examine the output, then change the order of function calls so that the temperature report prints after the precipitation report.

0.3.1 - Calling Functions From Other Functions

Consider this program:

def preamble():
  print("Today's weather forecast for Washington, DC is:")
  
def precipitation():
  print(" - 25% chance of rain")

def temperatures():
  print(" - High temperature of 84 degrees")
  print(" - Low temperature of 71 degrees")

def weather_report():
  preamble()
  temperatures()
  precipitation()

Note that the weather_report() program itself includes function calls to other programs.

Exercise 0.3.4

Exercise 0.3.4

Write the above program as function_calls.py.

  • When you run the program, nothing should print.
  • This is becuase the program only has no function calls, only function definitions!

Add one function call to print out the full report.

  • We have already been calling functions with other functions - remember, print() is a function!
  • There is no difference between calling functions we have defined and functions built in to Python.
def preamble():
  print("Today's weather forecast for Washington, DC is:")
  
def precipitation():
  print(" - 25% chance of rain")

precipitation()

def temperatures():
  print(" - High temperature of 84 degrees")
  print(" - Low temperature of 71 degrees")

temperatures()
preamble()

Functions can be defined and called in any order, but you must define a function before using it.

Exercise 0.3.5

Exercise 0.3.5

Look at the example above. What order do you expect the reports to print in? Move the call to preamble() before the call to precipitation() and save as call_order.py.

Mental execution:

  • We will use the term mental execution for the above exercise of tracing through the execution without actually compiling and running the program. Note: Mental execution is extremely important in developing programming skill
  • Practice this with every program you read or write. We can’t emphasisize this enough. Really.
  • Remember: execution starts at the top of a program and goes downwards. Function definitions are processed (understood) but not executed. When a function are invoked, execution “goes” into the function to execute the code in there.

0.3.2 - Function Names

Take a close look at the names of the functions in this program:

def preamble():
  print("Today's weather forecast for Washington, DC is:")
  
def temperatures():
  print(" - 25% chance of rain")

def rainfall():
  print(" - High temperature of 84 degrees")
  print(" - Low temperature of 71 degrees")

def weather_report():
  preamble()
  temperatures()
  rainfall()

weather_report()
  • Note that the function names temperatures() and rainfall() are “wrong” in that they do not logically (in English) reference the text they print out.

6 :::{.callout-caution appearance=“minimal”} ### Exercise 0.3.6 Write the above program as wrong_names.py. Run the program and observe the output - you will see that the program runs, even though it appears to have an “error.” :::

  • Function names are unique identifiers that you, the programmer, create.
  • Function names do not necessarily correspond to what the function does.
  • You could give your functions nonsensical names and, as long as they were valid and unique, your code would run.
  • It is a good practice to make your function names descriptive of their actual behavior.
    • This helps others read and understand your code.
    • This helps you understand code that you wrote earlier!

In the below example, we don’t use unique function names:

def rainfall():
  print(" - 25% chance of rain")

def rainfall():
  print(" - Partly cloudy")

rainfall()

Exercise 0.3.5

Exercise 0.3.7

Write the above program as rain_clash.py. Run it to see what the output is.

  • Note that the second definition overrides the first definition.

Change the name of the second functin that is defined (the one that prints ” - Partly cloudy”) to fix the name clash.

0.3.3 - Arguments

  • We have seen with the print() function that it is possible to have a function that performs an operation when given some variable.
  • We can have this behavior in functions that we write. The variable that the function acts on is called an argument.
def high_temp(todays_high):
  print("Today's high temperature will be ", end="")
  print(todays_high, end="")
  print(" degrees")

high_temp("93")
  • We defined a function with function name high_temp
  • By putting variable name todays_high inside the parentheses of the function definition:
    • We tell Python that the high_temp function will be called with an argument
    • We make the variable todays_high available for use later in the function
  • We print out todays_high in the body of the function
  • We call the function and pass an argument in the function call: high_temp("93")

Exercise 0.3.8

Exercise 0.3.8

Write the above program as function_argument.py. Change the argument to 94 and see how the output changes.

Be careful! Because we tell Python that the function requires an argument, we must pass an argument with the function call. The following code produces an error:

def high_temp(todays_high):
  print("Today's high temperature will be ", end="")
  print(todays_high, end="")
  print(" degrees")

high_temp()

0.3.4 - A Peek at the Future: Function Returns

So far, we have used functions to perform operations, in this case, printing text to the console. Functions can also be used to take some input and return an output.

Consider the following:

def twice(input_value):
  doubled_value = input_value * 2
  return doubled_value

y = twice(3)
  • The function twice takes an argument input_value
  • Inside the function, that value is multiplied by two and assigned to doubled_value
  • doubled_value is returned
  • The function does not print anything.
  • y takes on the value 6 (because the input, 3, is multipled by two)

Exercise 0.3.8

Exercise 0.3.8

Write the above program as function_return.py. Run it - observe that nothing prints. Add a print statement to print out the value of y and confirm the function’s operation.

For now, we won’t ask you to do anything return statements, but you should know that they exist. When you have to use them for problems, we’ll tell you exactly how to use them. Later in the course, you’ll use them extensively.

0.3.4 - Something Strange

Consider the following program:

def weather_report():
  print("The rain in Spain falls mainly on the plain")
  weather_report()

weather_report()
  • Examine the program above. Do not run it yet.
  • Mentally trace through the execution steps. Do you notice anything unusual?
  • Note that the function weather_report calls itself.
How To Stop A Running Program

Read this before attempting Exercise 0.3.9

Sometimes it is useful to stop a running program before it concludes on its own. A common reason to want to do this is a bug that causes an infinite loop.

For Spyder users, click the red rectangle above the output console to stop the running program. For Thonny users, click the red stop sign in the top bar of the editor. Both editors also respond to CTRL+C (holding the Control key and pressing the ‘C’ key).

The standard keyboard has some keys that act together with other keys, in effect modifying them. The Shift key is the most obvious one: pressing the shift key along with another key either capitalizes a letter or types the symbol “above” in a two-symbol key. For example, the ampersand (&) is “above” 7 on the same key as 7; thus, pressing Shift and 7 types &. On a Mac, you’ve probably used the Command key, and on Windows, you’ve used Control.

  • The Control key, when used with other keys, is often used in programming contexts.
  • One such case is to use Control + C (control and C together) to terminate the execution of a program.
  • However, to do this, you first need to click into wherever the program is executing. This is typically the output window (where the output appears).

Exercise 0.3.9

Exercise 0.3.9

Now, type up and execute the above program in infinity.py. What do you notice?

(Or you might get an “recursion depth exceeded” error.)

The term recursion is used when function calls itself: In the above example, it’s an obvious error. Nothing useful is accomplished. Later, we’ll learn to use recursion to solve problems. In fact, recursion is one of the most powerful computational problem-solving paradigms.

0.3.5 - Basic Computer Skills

If you’re still not confident about basic computer skills, review the tutorials and ask any questions you may have in lab or office hours.

End-Of-Module Problems

Full credit is 100 pts (complete at least three problems). There is no extra credit.

Problem 0.3.1 (40 pts)

Problem 0.3.1 (40 pts)

Modify the body of the conclusion() function so that the output of the program is:

We'll start at the beginning.
We'll finish at the end.

The program:

def introduction():
    print("We'll start at the beginning.")

def conclusion():
    # your code goes here

introduction()
conclusion()

Submit as introductory_functions.py

Problem 0.3.2 (40 pts)

Problem 0.3.2 (40 pts)

Complete the function incrementer() such that the function takes its argument, integer x, increases x by 1, and returns the new value of x.

def incrementer(x):
    # your code goes here
    return x

x = 5
y = incrementer(x)
print(y)

This should print out 6.

Submit as incrementing_function.py.

Problem 0.3.3 (40 pts)

Problem 0.3.3 (40 pts)

Write a function print_twice() that takes as argument a string, phrase, and prints that string twice on two separate lines.

def print_twice(phrase):
    # your code goes here

print_twice("I had 1500 kilometers ahead of me on the train")

When run, this should print:

I had 1500 kilometers ahead of me on the train
I had 1500 kilometers ahead of me on the train

Submit as twice_printed.py.

Problem 0.3.4 (40 pts)

Problem 0.3.4 (40 pts)

The function temperature() intends to print a temperature report based on argument today_temp (representing “today’s temperature”).

def temperature(today_temp):
    print("Today's temperature is ", end="")
    print(today_temp, end="")
    print(" degrees.")
    
temperature = 54
temperature(temperature)

This program has an error. Fix the error so that the function temperature() works correctly and the printed output is:

Today's temperature is 54 degrees.

Submit as temp_report.py.