You’ve seen a few examples of some basic functions so far. However, there are a few additional features of functions that we have yet to introduce, which will make them much more useful that functions on their own. In particular, these features are arguments/parameters, and return values.
The idea of a “function” actually originates from mathematics. In math, a function is some kind of operation / formula that accepts an input (typically a number) and gives some result (typically another number. If you’ve taken some basic algebra courses in high-school or college, you’ve probably already been introduced to this concept.
For example, you might have a mathematical “function” to take a number and double the value.
In this case we would have our function F(x) where The function F is defined as F(x) = x*2
.
If we say F(10)
this would give 20
.
If we say F(50)
this would give 100
.
In python programming, functions have a similar capability.
Arguments and Parameters (or for short, “args” and “params”) allow up to have functions that accept an input value from wherever the function is invoked.
A return value allows us to send a value back to the caller.
Lets implement the “multiply by two” function as a first, super simple example to demonstrate the concept:
1 def multiply_by_two(number):
2 new_number = number * 2
3 return new_number
4
5 r1 = multiply_by_two(10)
6 r2 = multiply_by_two(50)
7 print("Numbers:", r1, r2)
Some of this should look familiar from the last lesson that introduced functions, but some things will look new and unusual. Let’s break it down, line-by-line:
multiply_by_two
, similar to how I showed before.
The one “new” thing is the number
inside of the parentheses.
This is what we call a parameter.
Within the parentheses, we can specify a variable name, which will act as a storage location for a value that the caller of the function can pass in custom information.
This variable is one that can be used in the lines of our function.number
(which we don’t specifically know what it is) and multiply it by 2.new_number
variable, and return
is.
return
is a special keyword in python, that can only be used in code that is within a function.
This causes the function to stop at this point, and whatever value it to the right of it, it will send this back to wherever the function was called from in the code.multiple_by_two
function a value to multiply, we have to put something between the parentheses.
In this case, we give it 10
.
We call the value(s) within the parentheses at a call location arguments.
This means that when the function code executes, the number
parameter will be given the value of 10
.
The function will then return
a value of 20
, which will get saved into the variable r1
.number
parameter will be given the value of 50
.
The function will then return
a value of 100
, which will get saved into the variable r2
.Numbers: 20 100
.Recall that in the last lesson, we created a program that could give you feedback on the
def determine_golf_performance():
par = int(input('What par was the hole?\n'))
strokes = int(input('How many strokes did you use?\n'))
if par-3 == strokes:
print('Albatross')
elif par-2 == strokes:
print('Eagle')
elif par-1 == strokes:
print('Birdie')
elif par == strokes:
print('Par')
elif par+1 == strokes:
print('Bogey')
elif par+2 == strokes:
print('Double Bogey')
elif par+3 == strokes:
print('Triple Bogey')
else:
print('I don\'t know? Please try again.')
print(">> Use this tool to give you feedback on how you golfed")
hole = 1
while hole <= 18:
print(">> Hole", hole, "performance")
determine_golf_performance()
hole += 1
Though there are some exceptions to this, it not not good practice to have each function ask the user for the inputs it needs. This would get messy, because we would have many functions asking the user for inputs, and it would lead to restrictive program structure. We can restructure this program to be better organized with functions, and to use args/params/returns to help.
def determine_golf_performance(par, strokes):
if par-3 == strokes:
return 'Albatross'
elif par-2 == strokes:
return 'Eagle'
elif par-1 == strokes:
return 'Birdie'
elif par == strokes:
return 'Par'
elif par+1 == strokes:
return 'Bogey'
elif par+2 == strokes:
return 'Double Bogey'
elif par+3 == strokes:
return 'Triple Bogey'
else:
return '?'
def iterate_through_holes():
hole = 1
while hole <= 18:
par = int(input('What par was the hole?\n'))
strokes = int(input('How many strokes did you use?\n'))
result = determine_golf_performance(par, holes)
print("Hole", hole, "performance is", result)
hole += 1
print("Use this tool to give you feedback on how you golfed")
iterate_through_holes()
The program more or less does the same thing, but noticed how we utilized args/params/returns and one additional function.
A few lessons ago, I showed you some code that we could use to validate a phone number had correct formatting.
In this example, we can build off of that example, and write a program that simulates a user entering information on a form.
The form will ask the user for an email and phone number.
The program will have to tell the user if any of the information is not entered in correctly.
For the phone number, we want the format to still be XXX-XXX-XXXX
.
For the email, we want to confirm that there is exactly one @
sign and at least one .
.
Otherwise, the program should tell the user that all of the information is valid.
First off, we can take the code from the string iteration lesson for validating a phone number, change it slightly, and put it into a function:
def is_phone_valid(phone):
if len(phone) != 12 or phone[3] != '-' or phone[7] != '-':
return False
for i in range(0, 12):
if i != 3 and i != 7 and phone[i].isdigit() == False:
return False
return True
This function expects a string phone number as a parameter.
It will return the boolean value False
if it is not valid and True
if it is.
We will utilize this function later on.
Next, we need a function to validate the email address.
The validation we are going to do is pretty basic here.
As I said before, it is only checking for exactly one @
and at least one .
.
In reality, email formatting validation is more complex than this, but this is a good, simple starting point for the purposes of this exercise.
In fact, that’s one of the great things about code!
You can write a version of the code that is partly correct, and then iteratively improve upon it at a later time.
That’s a part of the reason why computer software needs updates and maintenance so often.
Anyways, our function for this could be implemented like so:
def is_email_valid(email):
at_count = 0
dot_count = 0
for character in email:
if character == '@':
at_count += 1
if character == '.':
dot_count += 1
return at_count == 1 and dot_count >= 1
Again, this function will return the boolean value True
if the email is good, and False
if not.
Now, we can write one more function.
This function’s role will be the primary logic of the program, with the printouts, asking the user for the input values, and calling the validation functions:
def main():
print("Welcome to the sign-up form.")
print("Please provide your email and phone number so we can contact you.")
number = input("Phone number: ")
address = input("Email Address: ")
number_valid = is_phone_valid(number)
address_valid = is_email_valid(address)
if number_valid and address_valid:
print("Thanks for providing your information")
else:
print("Something is not right. Please try again.")
Putting this all together, we end up with a program with three functions. One of these functions make calls to the other two to accomplish the overall task.
def is_phone_valid(phone):
if len(phone) != 12 or phone[3] != '-' or phone[7] != '-':
return False
for i in range(0, 12):
if i != 3 and i != 7 and phone[i].isdigit() == False:
return False
return True
def is_email_valid(email):
at_count = 0
dot_count = 0
for character in email:
if character == '@':
at_count += 1
if character == '.':
dot_count += 1
return at_count == 1 and dot_count >= 1
def main():
print("Welcome to the sign-up form.")
print("Please provide your email and phone number so we can contact you.")
number = input("Phone number: ")
address = input("Email Address: ")
number_valid = is_phone_valid(number)
address_valid = is_email_valid(address)
if number_valid and address_valid:
print("Thanks for providing your information")
else:
print("Something is not right. Please try again.")
main()
Here’s a few results of running this program:
Welcome to the sign-up form.
Please provide your email and phone number so we can contact you.
Phone number: 172-189-ABCD
Email Address: joe@email.com
Something is not right. Please try again.
Welcome to the sign-up form.
Please provide your email and phone number so we can contact you.
Phone number: 187-231-9872
Email Address: randyATgmail.org
Something is not right. Please try again.
Welcome to the sign-up form.
Please provide your email and phone number so we can contact you.
Phone number: 142-121-7918
Email Address: hal@email.edu
Thanks for providing your information