# # .. contents:: # # Download this page as: # # - :download:`a commented Python script ` # - :download:`a minimal Python script ` # # Writing Functions # ================= # # Basic syntax # ------------ # # As with other languages, you can write functions in Python to avoid # repeating code and to improve flow of your programs. Functions use a # similar indented syntax to the loops introduced earlier, with a colon # after the function name and the following lines indented. As with # loops, it is considered good python style to indent with four blank # space. Let's start by defining a simple function: # def my_function(): print("Hello World!") # This can be called with ``my_function()``: # my_function() # # .. note:: # It is considered good python style to have function names all in # lower case, with words separated by underscore if it improves # readability. # # This is a rather boring function that does not take nor return any # arguments. Let's make things a little more complicated: # def add_two_numbers(x1, x2): total = x1 + x2 return total y = add_two_numbers(3,5) print(y) # # This function simply adds the two numbers that it is given as # arguments. As you expect, we can pass integers, floats and strings to # a function. Actually, we can pass *any* Python object, even functions! You can # also return any number of arguments. # # Positional and keyword arguments # ---------------------------------- # # Consider the following function: # def print_argument(x=5): print(x) # # In this example, we have defined what the default value of the ``x`` # variable in the function. This is called a **keyword argument**, as opposed to # a **positional argument**. If you # try and call this function without any arguments, the default will be # used. If you call it with an argument, the specified value will be # used: # print_argument() print_argument(3.) print_argument(x=3.) # # .. admonition:: Exercise # # Write a function that prints the value of input argument # multiplied by 7. If no argument is given, it should print 7. If # the input argument is 6, it should print "The Answer to the Ultimate # Question of Life, The Universe, and Everything." # # .. raw:: html # #

Click to Show/Hide Solution

# def multiply_by_7(x=1): if x == 6: print("The Answer to the Ultimate Question of Life, " "the Universe and Everything.") else: print(x*7) multiply_by_7() multiply_by_7(4) multiply_by_7(6) # # .. raw:: html # #
# # Functions can have both **positional** and **keyword** and arguments. # The former are required (i.e. not giving them will result in a TypeError), the # latter are optional: # def slicer(seq, start=None, stop=None, step=None): """ Implement basic Python slicing.""" return seq[start:stop:step] l = [1, 2, 3, 4, 5, 6] slicer() slicer(l) slicer(l, stop=2) slicer(l, stop=5, step=2) # # # Docstrings # ---------- # # You can use a single string after the first line of a function to # describe what the function does and what its parameters are. The general # convention is: # def funcname(params): """Concise one-line sentence describing the function. Extended summary which can contain multiple paragraphs. """ # function body pass # # # Then the docstring for that function can be accessed with: # # # In [1]: help(funcname) # # In IPython you can access the same documentation using ``funcname?`` # (Try it now!).