.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/basics/functions.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_basics_functions.py: ================= 1.12 functions ================= .. important:: This lesson is still under development. .. GENERATED FROM PYTHON SOURCE LINES 11-25 A function is a box which takes something as input and it gives you output after performing some operations on that input. In python, the input and output arguments for a function are optional. The basic syntax of a minimal function in is as below .. code-block:: python def FunctionName(InputArguments): commands to find output return output As said earlier, `InputArguments` and ``return`` are optional. This means we can write a valid function in python without input arguments or a function which does not return something. .. GENERATED FROM PYTHON SOURCE LINES 27-33 .. code-block:: default def add_nums(): pass print(add_nums) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 34-37 .. code-block:: default type(add_nums) .. GENERATED FROM PYTHON SOURCE LINES 38-47 If we want to use/run a function, this means we want to **call** it. Following syntax can be used to call a function .. code-block:: python Output = FunctionName(InputArguments) ``Output`` is optional and so does ``InputArguments`` .. GENERATED FROM PYTHON SOURCE LINES 49-52 .. code-block:: default add_nums() .. GENERATED FROM PYTHON SOURCE LINES 53-54 The following function takes two input arguments and adds them .. GENERATED FROM PYTHON SOURCE LINES 56-63 .. code-block:: default def add_nums(a, b): # for brevity, we can not write add_nums(a+b): print('a: ', a, ' b:', b) a + b add_nums(1, 5) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 1 b: 5 .. GENERATED FROM PYTHON SOURCE LINES 64-65 Inside the function, we name the two input arguments as `a` and `b`. .. GENERATED FROM PYTHON SOURCE LINES 67-76 .. code-block:: default def add_nums(a, b): print('a: ', a, ' b:', b) a + b x = 12 y = 14 add_nums(x, y) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 12 b: 14 .. GENERATED FROM PYTHON SOURCE LINES 77-82 It is important to understant that the variable `a` and `b` are created once we are inside the function ``add_nums``. Outside function `12` is `x` but inside function, `12` is `a`. The variables `a` and `b` are not available outside the function. .. GENERATED FROM PYTHON SOURCE LINES 84-94 .. code-block:: default def add_nums(a, b): print('a: ', a, ' b:', b) c = a + b return c x = 12 y = 14 add_nums(x, y) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 12 b: 14 26 .. GENERATED FROM PYTHON SOURCE LINES 95-100 Above we we created `c` inside the function and returned it using the ``return`` statement. Outside the function when we `called` the function `add_nums` by executing ``add_nums(x,y)``, this value of `c` is printed. The variable named `c` itself is not available outside the function. The variables which can be seen inside the function and which can be seen outside the function will be covered in :ref:`sphx_glr_auto_examples_basics_global_vs_local.py`. .. GENERATED FROM PYTHON SOURCE LINES 104-109 Return ------- A function returns ``None`` by default. The value returned by a function can be assigned to a new variable for example to `x` in following example. It can be any legal variable name though. .. GENERATED FROM PYTHON SOURCE LINES 111-122 .. code-block:: default import random # ignore this line if you don't know what it does qatleen = ['winsten churchil', 'rana sanaullah', 'obama', 'musharaf'] def print_qatal(): print(random.choice(qatleen)) return None x = print_qatal() print('type of x: ', type(x)) .. rst-class:: sphx-glr-script-out .. code-block:: none musharaf type of x: .. GENERATED FROM PYTHON SOURCE LINES 123-124 Even if a function does not return anything explicitly, it still returns ``None``. .. GENERATED FROM PYTHON SOURCE LINES 126-135 .. code-block:: default def print_qatal(): print(random.choice(qatleen)) return x = print_qatal() print('type of x: ', type(x)) .. rst-class:: sphx-glr-script-out .. code-block:: none musharaf type of x: .. GENERATED FROM PYTHON SOURCE LINES 136-137 If a function does not have ``return`` statement, it still returns ``None``. .. GENERATED FROM PYTHON SOURCE LINES 139-146 .. code-block:: default def print_qatal(): print(random.choice(qatleen)) x = print_qatal() print('type of x: ', type(x)) .. rst-class:: sphx-glr-script-out .. code-block:: none rana sanaullah type of x: .. GENERATED FROM PYTHON SOURCE LINES 147-148 So it is impossible in python to write a function which returns absolutely nothing. .. GENERATED FROM PYTHON SOURCE LINES 150-162 .. code-block:: default def add_nums(a, b): print('a: ', a, ' b:', b) c = a + b return c x = 12 y = 14 z = add_nums(x, y) print('The function returns z: ', z) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 12 b: 14 The function returns z: 26 .. GENERATED FROM PYTHON SOURCE LINES 163-166 The variables `c` and `z` have same values with the difference that `c` exists only inside the function. Moreover, the creation of `c` is not necessary, we can just return the result as it is. .. GENERATED FROM PYTHON SOURCE LINES 166-176 .. code-block:: default def add_nums(a, b): print('a: ', a, ' b:', b) return a + b # no intermediate variable c x = 12 y = 14 z = add_nums(x, y) print('The function returns z: ', z) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 12 b: 14 The function returns z: 26 .. GENERATED FROM PYTHON SOURCE LINES 177-190 **Question**: What value will be printed as a result of code in following cell? .. code-block:: python def add_nums(a, b): print('a: ', a, ' b:', b) z = a + b x = 12 y = 14 z = add_nums(x, y) print('The function returns z: ', z) .. GENERATED FROM PYTHON SOURCE LINES 192-205 **Question**: What value will be printed as a result of code in following cell? .. code-block:: python def add_nums(a, b): print('a: ', a, ' b:', b) c = a + b x = 12 y = 14 add_nums(x, y) print('The value of c is: ', c) .. GENERATED FROM PYTHON SOURCE LINES 207-221 **Question**: What value will be printed as a result of code in following cell? .. code-block:: python def add_nums(a, b): print('a: ', a, ' b:', b) c = a + b return c x = 12 y = 14 add_nums(x, y) print('The value of c is: ', c) .. GENERATED FROM PYTHON SOURCE LINES 223-237 **Question**: What value will be printed as a result of code in following cell? .. code-block:: python def add_nums(a, b): print('a: ', a, ' b:', b) c = a + b return c x = 12 y = 14 z = add_nums(x, y) print('The value of c is: ', c) .. GENERATED FROM PYTHON SOURCE LINES 239-253 **Question**: What value will be printed as a result of code in following cell? .. code-block:: python def add_nums(a, b): print('a: ', a, ' b:', b) c = a + b return c x = 12 y = 14 z = add_nums(x, y) print('The value of z is: ', c) .. GENERATED FROM PYTHON SOURCE LINES 255-260 Default values of input arguments --------------------------------- We can provide default values to input arguments. The default values of input arguments are only used if we don't provide their values when calling them, otherwise their values are overwritten. .. GENERATED FROM PYTHON SOURCE LINES 262-272 .. code-block:: default def add_nums(a=12, b=14): print('a: ', a, ' b:', b) return a + b x = 114 y = 313 z = add_nums(x, y) print('The function returns z: ', z) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 114 b: 313 The function returns z: 427 .. GENERATED FROM PYTHON SOURCE LINES 273-279 Above: The value from variable `x` is going to `a` and will replace its default value. The value from variable `y` will go to `b` and will overwrite its default value i.e. 14. When we have defined the default values of input arguments in function definition, we can skip one or more input arguments when calling the function as shown below. .. GENERATED FROM PYTHON SOURCE LINES 281-290 .. code-block:: default def add_nums(a=12, b=14): print('a: ', a, ' b:', b) return a + b y = 313 z = add_nums(y) print('The function returns z: ', z) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 313 b: 14 The function returns z: 327 .. GENERATED FROM PYTHON SOURCE LINES 291-292 Above, the value from `y` will be assigned to `a` while `b` will use its default value. .. GENERATED FROM PYTHON SOURCE LINES 294-303 .. code-block:: default def add_nums(a=12, b=14): print('a: ', a, ' b:', b) return a + b y = 313 z = add_nums(b=y) print('The function returns z: ', z) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 12 b: 313 The function returns z: 325 .. GENERATED FROM PYTHON SOURCE LINES 304-305 Above, `a` will use its default value while `b` will get value of `y`. .. GENERATED FROM PYTHON SOURCE LINES 307-317 .. code-block:: default def add_nums(a=12, b=14): print('a: ', a, ' b:', b) return a + b x = 114 z = add_nums(a=x) print('The function returns z: ', z) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 114 b: 14 The function returns z: 128 .. GENERATED FROM PYTHON SOURCE LINES 318-320 Above: `a` will use the value of `x` i.e. 114 while `b` will use its default value i.e. 14. .. GENERATED FROM PYTHON SOURCE LINES 322-330 .. code-block:: default def add_nums(a=12, b=14): print('a: ', a, ' b:', b) return a + b z = add_nums(1) print('The function returns z: ', z) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 1 b: 14 The function returns z: 15 .. GENERATED FROM PYTHON SOURCE LINES 331-334 Above, `1` will go to `a` while `b` will use its default value. The function can also be called without providing any input argument because both input arguments are optional. In this case the default values will be used. .. GENERATED FROM PYTHON SOURCE LINES 336-344 .. code-block:: default def add_nums(a=12, b=14): print('a: ', a, ' b:', b) return a + b z = add_nums() print('The function returns z: ', z) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 12 b: 14 The function returns z: 26 .. GENERATED FROM PYTHON SOURCE LINES 345-347 We can define the optional arguments with obligatory arguments. In function below, `c` is optional, while `a` and `b` are obligatory. .. GENERATED FROM PYTHON SOURCE LINES 349-357 .. code-block:: default def add_nums(a, b, c=14): print('a:', a, ' b:', b, ' c:', c) return a + b z = add_nums(1, 2) print('The function returns z: ', z) .. rst-class:: sphx-glr-script-out .. code-block:: none a: 1 b: 2 c: 14 The function returns z: 3 .. GENERATED FROM PYTHON SOURCE LINES 358-360 Above, we have not provided the value for `_c`. As it was optional argument, its default value was used. .. GENERATED FROM PYTHON SOURCE LINES 362-364 **Question**: What will be the output of following function? .. GENERATED FROM PYTHON SOURCE LINES 366-370 .. code-block:: python z = add_nums() print('The function returns z: ', z) .. GENERATED FROM PYTHON SOURCE LINES 372-374 **Question**: Guess the output from following cell. .. GENERATED FROM PYTHON SOURCE LINES 376-381 .. code-block:: python z = add_nums(a=1, c=313) print('The function returns z: ', z) .. GENERATED FROM PYTHON SOURCE LINES 384-388 Returning multiple values ------------------------- If a function returns more than one object/variables, and we assign it to a single variable, then this new variable will be ``tuple``. .. GENERATED FROM PYTHON SOURCE LINES 388-397 .. code-block:: default def func(a, b): u = a v = b return u, v xx = func(5, 12) print(xx, type(xx)) .. rst-class:: sphx-glr-script-out .. code-block:: none (5, 12) .. GENERATED FROM PYTHON SOURCE LINES 398-404 Above: The function returns 2 arguments but we assigned it to 1 variable named `xx`. Thus, `xx` will be a tuple consisting of two values We can however, assign both returned values from a function to two new variables as shown below. %% .. GENERATED FROM PYTHON SOURCE LINES 404-409 .. code-block:: default xx, yy = func(5, 12) print(xx, type(xx)) print(yy, type(yy)) .. rst-class:: sphx-glr-script-out .. code-block:: none 5 12 .. GENERATED FROM PYTHON SOURCE LINES 410-412 If the function returns fewer or more arguments than the variables assigned, then it will give error. .. GENERATED FROM PYTHON SOURCE LINES 414-418 .. code-block:: default # uncomment the following line # xx, yy, zz = func(5, 12) # Error .. GENERATED FROM PYTHON SOURCE LINES 419-421 If the function returns multiple values but we want to get only first value, we can do it as below .. GENERATED FROM PYTHON SOURCE LINES 423-427 .. code-block:: default xx = func(15, 12)[1] print(xx) .. rst-class:: sphx-glr-script-out .. code-block:: none 12 .. GENERATED FROM PYTHON SOURCE LINES 428-430 Above, we are slicing the output of `func` using `[1]` to get the second value. The type of the returned value will be the same as the type of the value returned by the function. .. GENERATED FROM PYTHON SOURCE LINES 432-439 .. code-block:: default def retun_list(a): return [a] out = retun_list(10) print(type(out)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 440-441 A function can return a tuple in following ways .. GENERATED FROM PYTHON SOURCE LINES 441-447 .. code-block:: default def return_tuple(variable): return variable, variable out = return_tuple(10) print(type(out)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 448-454 .. code-block:: default def return_tuple(variable): return variable, out = return_tuple(10) print(type(out)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 455-462 .. code-block:: default def return_tuple(variable): return (variable) out = return_tuple(10) print(type(out)) .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 463-466 The type of `out` is ``int`` because it is comma ``,`` which makes something a tuple not the brackets. So in order to get a tuple from function, we must put comma even if there is only one object in the tuple as shown below. .. GENERATED FROM PYTHON SOURCE LINES 468-475 .. code-block:: default def return_tuple(variable): return (variable, ) out = return_tuple(10) type(out) .. GENERATED FROM PYTHON SOURCE LINES 476-485 .. code-block:: default def return_tuple(variable): return variable, variable+2, variable+4 var, *junk = return_tuple(2) print(type(var), var) print(type(junk), junk) .. rst-class:: sphx-glr-script-out .. code-block:: none 2 [4, 6] .. GENERATED FROM PYTHON SOURCE LINES 486-487 A common way to ignore the unncessary output from a function is to use underscore .. GENERATED FROM PYTHON SOURCE LINES 487-490 .. code-block:: default var, *_ = return_tuple(2) .. GENERATED FROM PYTHON SOURCE LINES 491-494 **Question**: What will be the length of ``_`` above? .. GENERATED FROM PYTHON SOURCE LINES 496-498 Above we were interested in only `var` and wanted to ignore everything else returned by `return_tuple` function. .. GENERATED FROM PYTHON SOURCE LINES 500-502 calling a function from another function ---------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 502-511 .. code-block:: default def foo(a): return a + 1 def bar(a): return foo(a) + 1 bar(1) .. rst-class:: sphx-glr-script-out .. code-block:: none 3 .. GENERATED FROM PYTHON SOURCE LINES 512-514 Above we are calling function `foo` from inside function `bar`. The output of `foo` is added with 1 and returned by `bar`. .. GENERATED FROM PYTHON SOURCE LINES 516-530 .. code-block:: default def foo(a): return a + 1 def bar(a): return a+100 def baz(a): b = foo(a) b = bar(b) return b baz(1) .. rst-class:: sphx-glr-script-out .. code-block:: none 102 .. GENERATED FROM PYTHON SOURCE LINES 531-534 Above we are calling function `foo` from inside function `baz`. The output of `foo` is assigned to variable `b` and then `bar` is called with `b` as input argument. The output of `bar` is again assigned to `b` and returned by `baz`. .. GENERATED FROM PYTHON SOURCE LINES 536-556 **Question**: .. code-block:: python def add_nums(a, b): return a + b def sub_nums(a, b): return a - b def multiply_nums(a, b): return a * b def divide_nums(a, b): return a / b Write a function named `foo` in such a way that you call all the above four functions (`add_nums`, `sub_nums`, `multiply_nums`, `divide_nums`) from inside `foo`. The `foo` function should take two input arguments and return 100. You can create intermediate variables as well. .. GENERATED FROM PYTHON SOURCE LINES 558-563 function as input argument --------------------------- The input arguments to a function can be any python object. This includes functions as well. We can assign a function to a variable and use that variable to call the function. .. GENERATED FROM PYTHON SOURCE LINES 565-573 .. code-block:: default def print_me(to_print): print(to_print) x = print_me x('This goes into print_me') .. rst-class:: sphx-glr-script-out .. code-block:: none This goes into print_me .. GENERATED FROM PYTHON SOURCE LINES 574-575 Thus we can use functions as input arguments to other functions as well. .. GENERATED FROM PYTHON SOURCE LINES 577-587 .. code-block:: default def magic(left, op, right): return op(left, right) def my_op(var_a, var_b): return var_a == var_b magic(2, my_op, 2) .. rst-class:: sphx-glr-script-out .. code-block:: none True .. GENERATED FROM PYTHON SOURCE LINES 588-594 positioning of ``return`` statement ----------------------------------- It is important to understand that the function will exit as soon as it encounters a ``return`` statement. This means that the code after the ``return`` statement will not be executed. .. GENERATED FROM PYTHON SOURCE LINES 596-602 .. code-block:: default def add_nums(a, b): return a + b print('This will not be printed') add_nums(1, 2) .. rst-class:: sphx-glr-script-out .. code-block:: none 3 .. GENERATED FROM PYTHON SOURCE LINES 603-616 .. code-block:: default def add_nums(a_list, break_point=5): _sum = 0.0 for val in a_list: _sum += val if _sum > break_point: break return _sum x = add_nums([1, 2, 3, 4, 5]) print(x) .. rst-class:: sphx-glr-script-out .. code-block:: none 6.0 .. GENERATED FROM PYTHON SOURCE LINES 617-619 As soon as the value of `_sum` became greater than `break_point`, the ``for`` loop exited and we got the value of `_sum` at that point. .. GENERATED FROM PYTHON SOURCE LINES 621-625 .. code-block:: default x = add_nums([1, 2, 3, 4, 5], 50) print(x) .. rst-class:: sphx-glr-script-out .. code-block:: none 15.0 .. GENERATED FROM PYTHON SOURCE LINES 626-628 **Question:** Was the ``break`` statement executed above? .. GENERATED FROM PYTHON SOURCE LINES 630-641 **Question**: What will be the output of following code? .. code-block:: python def foo(a,b): c = a+b return c c = a-b z = foo(1,2) print(z) .. GENERATED FROM PYTHON SOURCE LINES 643-655 **Question**: What will be the output of following code? .. code-block:: python def foo(a,b): c = a+b return c c = a-b return c z = foo(1,2) print(z) .. GENERATED FROM PYTHON SOURCE LINES 657-667 **Question**: What will be the output of following code? .. code-block:: python def foo(a,b): if a==0: return b else: return foo(a-1, a+b) .. GENERATED FROM PYTHON SOURCE LINES 669-673 docstring ---------- The first string inside the functions is usually put for help. This is called `docstring`. It can be called by ``__doc__`` method .. GENERATED FROM PYTHON SOURCE LINES 675-682 .. code-block:: default def fahrenheit(T_in_celsius): """This function converts temperature from Celsius to Fahrenheit. """ return (T_in_celsius * 9 / 5) + 32 fahrenheit.__doc__ .. rst-class:: sphx-glr-script-out .. code-block:: none 'This function converts temperature from Celsius to Fahrenheit. ' .. GENERATED FROM PYTHON SOURCE LINES 683-686 .. code-block:: default help(fahrenheit) .. rst-class:: sphx-glr-script-out .. code-block:: none Help on function fahrenheit in module __main__: fahrenheit(T_in_celsius) This function converts temperature from Celsius to Fahrenheit. .. GENERATED FROM PYTHON SOURCE LINES 687-688 If we want to know the name of a function as string we can do it as following. .. GENERATED FROM PYTHON SOURCE LINES 690-694 .. code-block:: default converter = fahrenheit print(converter.__name__) .. rst-class:: sphx-glr-script-out .. code-block:: none fahrenheit .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.016 seconds) .. _sphx_glr_download_auto_examples_basics_functions.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/AtrCheema/python-seekho/master?urlpath=lab/tree/notebooks/auto_examples/basics/functions.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: functions.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: functions.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_