.. _functions: Functions ========= What is a function? ^^^^^^^^^^^^^^^^^^^ Functions are neat little machines that use some inputs to give us outputs. .. image:: _static/img/functions.png :align: center When looking at a machine from the outside we don't really care how it works, we just care that it does; Imagine a vending machine, you put in a number, you give it money and it gives you back a certain snack. It's the same thing with functions, you or someone else **builds** the function ONCE, and then you **use** it as many times as you want without thinking too much about how it works. .. note:: When you build a function, programmers call that **defining** the function. While when you use a function, programmers say that you're **calling** the function. Functions are a very neat trick that saves programmers a lot of time, by making code smaller and easier to read. How to create and use functions in Python? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ We first need to define our function before calling it: .. code-block:: python def hello(name): print("Hello", name) This is a very simple function which can be used for greeting any person: it takes in that person's name and then prints a customized greeting. Let's try calling it a few times and see what happens: .. code-block:: python def hello(name): print("Hello", name, "!") hello('stranger') hello('python') hello('world') This function is very basic, but still useful: we don't have to repeat the code inside the function over and over. And if we want to change the greeting, we can simply change our 'hello' function's definition. See how easy it is to modify it: .. code-block:: python def hello(name): print("Hello", name, ", how are you?") hello('stranger') hello('python') hello('world') | Generally functions can be as small as this one or as big as a whole page, it all depends on what we want our function to do. There are also multiple types of functions: some functions are used just to do printing, like this one. While others can perform complicated calculations and then return an answer to us. Check out this code example below which uses a function to calculate the surface of a circle: .. code-block:: python def circle_surface(radius): surface = 3.141592654*radius*radius return surface radius1 = 1 radius2 = 2 #calculate surface of a 1m radius circle circle1 = circle_surface(radius1) #calculate surface of a 2m radius circle circle2 = circle_surface(radius2) print("Circle 1: radius =", radius1, "m, area =", circle1, "m2") print("Circle 2: radius =", radius2, "m, area =", circle2, "m2") | .. warning:: You **cannot** use spaces when naming your functions and variables. Use _ (underscores) instead. For example: instead of writing *circle surface*, you can write *circle_surface*! |