:tocdepth: 2 .. _functions00: Functions, IIa: Definition and arguments ============================================================================ .. contents:: :local: .. highlight:: python Conceptually, a **function** is a piece of a program, a set of instructions arranged in order to carry out one or more well-defined tasks. We distinguish two categories of functions in Python, the *predefined* functions and the *user-written* ones: - The predefined functions are functions directly integrated into the standard library (what are called **built-in** functions) and into modules of the Python system (which we saw in discussion :ref:`importing modules `). - User functions are written either by the current user or by other users. These can be placed directly in a program/script, or imported, as well. Some predefined functions in python ----------------------------------- The function ``print()``: As we have :ref:`already seen `, this function has the role of displaying on the screen the values of the objects specified as arguments: .. code:: python print("Good morning", "to", "all of you") x=12 print(x) y=[1, "Monday","12", 5, 3, "test value"] print(y) You can replace the default separator (space) by any other character (or even with no characters), thanks to the argument\ ``sep``: .. code:: python print("Good morning", "to", "all of you", sep= "****") print(""Good morning", "to", "all of you", sep= "") - The ``input ()`` function: The \*\* input () \*\* function allows you to give the user control so that he enters the value of a given argument: .. code:: python first_name = input("Enter you first name : ") print("Bonjour,", first_name) .. code:: python print("Please enter any positive number: ", end=" " ) ch = input() num = int(ch) # converting string to integer print("The square of", num, "is", num**2) .. note:: Note that the ``input()`` function always returns a string. If you want the user to enter a numeric value, so you will need to convert the value input (which will therefore be of type string anyway) into a numerical value of the type you suitable, via the built-in functions ``int()`` (if you expect an integer) or ``float()`` (if you are expecting a real one). User-defined functions ----------------------- Defining a function ~~~~~~~~~~~~~~~~~~~~~ When there is not an available function to perform a task, you can write your own functions. The simplest functions have the following format in Python: :: def (): .. code-block:: python # define a function def do_nothing(): s = "I don't do much" # call a function do_nothing() However, this often isn’t very useful since we haven’t returned any values from this file. Note that if you don’t return anything from a function in Python, you implcitly have returned the special ``None`` singleton. .. code-block:: python def do_nothing(): s = "I don't do much" output = do_nothing() type(output) \.\.\. which produces: .. parsed-literal:: NoneType To return vaulues that you computed locally in the function body, use the **return** keyword. To define a function in Python, we use the keyword ``def`` to specify the name of the function. The basic syntax for defining a function is as follows: .. image:: media/function1.png :width: 450 :align: center :alt: function1 Definition of a function without arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code:: ipython3 def hello_function(): print('Hello World, it is me. I am a function.') You call it doing: .. code:: ipython3 hello_function() .. parsed-literal:: Hello World, it is me. I am a function. The example below illustrates the definition of a simple function without arguments and a return instruction. .. code:: ipython3 def return_me(): s = 'Hello World, it is me. I am a function.' return s .. code:: ipython3 return_me() .. parsed-literal:: 'Hello World, it is me. I am a function.' The output looks the same for the functions but remember, there is a difference between what Python displays and what Python knows about what it displays. So if we set: .. code:: ipython3 r = hello_function() t = return_me() # We can see that type(r) # returns the argument of the argument of the print function type(t) # a string .. parsed-literal:: Hello World, it is me. I am a function. .. parsed-literal:: str Definition of a function with arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Computer scientists' functions acquire their full potential with: - an input, which groups together variables that serve as arguments, - an output, which is a result returned by the function (and which often will depend on the arguments entry). Function with one argument ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Functions, may be defined to take parameters or **arguments**. :: def (): return The function name, arguments, and return are jointly known as the **function signature** since the uniquely define the function’s **interface**. Using a function is done by placing parentheses ``()`` after the function name after you have defined it. This is known as **calling** the function. If the function requires arguments, the values for these arguments are inside of the parentheses .. raw:: html
.. raw:: html
.. image:: media/function2.png :width: 450 :align: center :alt: function2 .. code:: ipython3 def square(x): sqr = x * x return sqr .. code:: ipython3 square(2) .. parsed-literal:: 4 Function with (multiple) arguments/(multiple) return values, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ There may be multiple input arguments, there may be multiple output results. That is, functions may be defined such that they have multiple arguments or multiple return values: :: def (, , ...): return , , ... .. image:: media/function3.png :width: 450 :align: center :alt: function3 - Comments and docstring - Anything after the pound sign # is a comment and is ignored by Python: .. code:: python # Main loop while r != 0: # As long as r is non zero r = r - 1 # Reduce by 1 - You can describe what a function does by starting with a docstring, that is to say adescription, surrounded by three quotation marks: .. code:: python def produit(x,y): """ Calculate the product of two numbers Input: two numbers x and y Output: the product of x by y""" p = x * y return p Here is an example of a function with two arguments and two outputs. .. code:: ipython3 def sum_prod(x,y): """ Computes the sum and product of two numbers. """ #Sum S = x + y # Product P = x*y return S, P # Returns the results # Calling the function Sum, prod = sum_prod(3,7) # Results # Display print("Sum :",Sum) print("Product :",prod) .. parsed-literal:: Sum : 10 Product : 21 Function with a variable number of arguments ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ It might happen that one does not know in advance the exact number of input arguments a function will take. That is, functions may be defined such that they have a variable number of arguments: :: def (*args): return , , ... Here is an example of such function which takes a variable number of arguments and return their sum and their product. .. code:: ipython3 def sum_prod(*args): """ Computes the sum and product of its arguments. """ #Sum S = 0 # Product P = 1 for value in args: S += value P *= value return S, P # Returns the results # Calling the function Sum, Prod = sum_prod(3,7,1,2) # Results # Display print("Sum :",Sum) print("Product :",Prod) .. parsed-literal:: Sum : 13 Product : 42 Keyword Arguments ^^^^^^^^^^^^^^^^^ In Python, functions also support options default values for arguments. Arguments with an associated default are called **keyword arguments**. If this function is then called without one of these arguments being pesent the default value is used. All keyword arguments must come after normal arguments in the function definition: :: def (, , =, =, ...): return .. code:: ipython3 def add_space(s, t="Mom"): return s + " " + t .. code:: ipython3 print(add_space("Hello")) print(add_space("Morning", "Dad")) .. parsed-literal:: Hello Mom Morning Dad You can also call any functions with their arguments, regular and keyword, with their argument names explicitly in the call. This uses equal signs in the same way that keyword arguments are defined. .. code:: ipython3 print(add_space(s="Hello")) print(add_space(s="Morning", t="Dad")) .. parsed-literal:: Hello Mom Morning Dad If you have many keyword arguments, then they may be out of order in function call as long as they are explicit. .. code:: ipython3 def f(x=1, y=2, z=3): return 2*x**3 + 42*y - z .. code:: ipython3 f(y=17, z=15, x=2) .. parsed-literal:: 715 **Warning:** be careful with mutable containers and default values. The value changes with every function call. .. code:: ipython3 def add_to_list(val, seq=[]): seq.append(val) return seq .. code:: ipython3 add_to_list(42) .. parsed-literal:: [42] .. code:: ipython3 add_to_list(16) .. parsed-literal:: [42, 16] .. code:: ipython3 add_to_list(39) .. parsed-literal:: [42, 16, 39] Practice ----------------------------- #. Write a Python function to find the maximum of three numbers. #. Write a Python function to sum all the even numbers in a list. #. Write a Python function to multiply all the odd numbers in a list. #. Write a Python function to calculate the factorial of a a non-negative integer. #. Write a Python function to check whether a number is in a given range. #. Write a Python function that takes :math:`x` as argument and returns :math:`y` computed as .. math:: y = 6x^3 + 3x^2 + 5x+1 #. Write a Python function ``f(n)`` for computing the element :math:`x_n` in the sequence :math:`x_n=n^2-1`. Call the function for :math:`n=6` and write out the result. #. Write a Python function for evaluating the mathematical function :math:`f(x)=\cos(4x)` and its derivative :math:`f'(x)=-4\sin(4x)`. Note: the function returns 2 values. #. Write a Python function for evaluating the mathematical function :math:`f(x)=e^{-x}\sin (4x)` #. Write a Python function for evaluating the mathematical function .. math:: s(t; v_0, a) = v_0t + \frac{1}{2}at^2 #. Write a Python function to convert a temperature given in degrees Fahrenheit to its equivalent in degrees Celsius. You can assume that :math:`T_c = (5/9) \times (T_f - 32)`, where :math:`T_c` is the temperature in °C and :math:`T_f` is the temperature in °F. #. Write a Python function that takes a number as a parameter and checks if the number is prime or not. #. Write a function that displays the n first terms of the Fibonacci sequence, defined by: .. math:: \left\{ \begin{array}{ll} U_{0} = 0 \\ U_{1} = 1 \\ U_{n+2} = U_{n+1} + U_{n} \end{array} \right.