In [1]:
def plus_one(x):
return x + 1
In [2]:
plus_one(1)
Out[2]:
In [3]:
plus_one(2)
Out[3]:
or complex
In [4]:
def do_math(x):
return (x * 2.)/(x - 1.)
In [5]:
do_math(2)
Out[5]:
In [6]:
do_math(42)
Out[6]:
You can call functions from within other functions.
In [7]:
def abra(s):
return "Abra " + s
def alakazam(s):
return abra(s) + " Alakazam"
alakazam("Kadabra")
Out[7]:
Functions can have lots of arguments/parameters
In [8]:
def all_the_params(a, b, c, d):
return a + b + c + d
all_the_params(1, 2, 3, 4)
Out[8]:
or no arguments
In [9]:
def toop():
return "toop"
toop()
Out[9]:
Functions can take pretty much anything as arguments, including other functions.
In [10]:
def call_it_twice(fun):
return fun() + " " + fun()
call_it_twice(toop)
Out[10]:
Functions can also return functions
In [11]:
def print_it_twice(number):
def x():
return number + " " + number
return x
a_fun = print_it_twice("Double")
a_fun
Out[11]:
Here a_fun is a function which you can call like any other function
In [12]:
a_fun()
Out[12]:
In [13]:
def with_defaults(x, y = 2, z = 3):
print(x, y, z)
return x + y + z
In [14]:
with_defaults(1) # Using both default values.
Out[14]:
In [15]:
with_defaults(1, 1) # Using one default value.
Out[15]:
In [16]:
with_defaults(1, 1, 1) # Using no default values.
Out[16]:
If you wanted to change only z but not y you can used a keyword argument.
In [17]:
with_defaults(1, z = 4) # Use the default value for y but not z.
Out[17]:
This is useful for dealing with functions with lots of default values when you only want to change some of the defaults.
In [18]:
def deeper():
return deeper()
deeper()
Though unless your function stops calling itself you're going to have issues.
In [19]:
def sum_up_to(x):
print(x)
if x <= 0: return 0
else: return x + sum_up_to(x - 1)
sum_up_to(4)
Out[19]:
In [20]:
def no_return(x):
x + x
a_thing = no_return(42)
print(a_thing)
If you forget to include () when calling a function
In [21]:
print(toop) # Incomplete
you get back the function itself as opposed to the result of the function