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
- 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
- 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. Theprint
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.
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 afterprecipitation()
temperatures()
is called beforeprecipitation()
Exercise 0.3.3
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
- 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
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()
andrainfall()
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:
Exercise 0.3.5
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")
"93") high_temp(
- 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 tell Python that the
- 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
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):
= input_value * 2
doubled_value return doubled_value
= twice(3) y
- The function
twice
takes an argumentinput_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
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.
Exercise 0.3.9
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.