You now know how to run Python code, assign variables, and write control flow statements, which allows us to write programs that can do calculations. In fact, this is all you really need to write programs (except for being able to read in and write out data which we will talk about later). However, with only this, programs will quickly become very long and unreadable. So one very important rule in programming is to avoid repetition.
The syntax for a function is:
def function_name(arguments):
# code here
return values
Functions are the building blocks of programs - think of them as basic units that are given a certain input an accomplish a certain task. Over time, you can build up more complex programs while preserving readability.
Similarly to if
statements and for
and while
loops, indentation is very important because it shows where the function starts and ends.
Note: it is a common convention to always use lowercase names for functions.
A function can take multiple arguments...
def add(a, b):
return a + b
print(add('1','3'))
print(add(1.,3.2))
print(add(4,3.))
... and can also return multiple values:
def double_and_halve(value):
return value * 2., value / 2.
print(double_and_halve(5.))
If multiple values are returned, you can store them in separate variables.
d, h = double_and_halve(5.)
print(d)
print(h)
Functions can call other functions:
def do_a_and_b():
do_a()
do_b()
def do_a():
print("doing A")
def do_b():
print("doing B")
do_a_and_b()
Figuring out the right functions is half the trick behind a good program. A good function has a clear purpose that can, ideally, be described in one sentence of natural language.
Beginners typically err on the side of defining too few functions and writing monsters spanning a couple of screen pages. That's a clear indication that you're doing it wrong. A good function can be taken in (albeit perhaps not understood) at a glance.
Copy your code that finds prime numbers here and modify it so as to make it a function that given a number will return True
or False
depending on whether it is prime.
# enter your solution here
Write a function that will return the digit sum of a number (e.g. for 1989 it is 1+9+8+9=27
).
# enter your solutions here
In addition to normal arguments, functions can take optional arguments that can default to a certain value. For example, in the following case:
def say_hello(first_name, middle_name='', last_name=''):
print("First name: " + first_name)
if middle_name != '':
print("Middle name: " + middle_name)
if last_name != '':
print("Last name: " + last_name)
we can call the function either with one argument:
say_hello("Douglas")
and we can also give one or both optional arguments (and the optional arguments can be given in any order):
say_hello("Douglas", last_name="Adams")
say_hello("Douglas", middle_name="Noel", last_name="Adams")
say_hello("Douglas", last_name="Adams", middle_name="Noel")
You may have already noticed that there are functions that are defined by default in Python:
x = [1,3,6,8,3]
len(x)
sum(x)
int(1.7)
A full list of built-in functions is available from http://docs.python.org. Note that there are not that many - these are only the most common functions. Most functions are in fact kept inside modules, which we will cover later.
Write a function that takes a list, and returns the mean and the standard deviation of the values in the list. Test it with the following list:
l = [1, 9, 4, 5, 16, 7]
# enter your solution here