Skip to content
Permalink
7ae7d3de3a
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
22 lines (16 sloc) 1.78 KB

Functions

Functions are self contained objects that are used to create code that we often want to reuse. The most arbitrary use of a function is in this code:

{{ code_from_file("conditionals/example-1.py", 1, 9, execute=True) }}

As you can see, we have created our first function. To create a function you must first use the def keyword followed by the name for the function. The naming conventions for functions are the same as they are for variables. However, it is good practice to have descriptive names for your functions so that you can recognise what they do at a glance.

The shape of a user defined function is always of the form:

def name_of_function(passed_variable):
    <contents of the function,>
    <indented even across>
    <multiple lines.>

The contents of the function is always indented to show that it belongs to the function definition above it. Python then knows that this is the local scope of that function and looks there first for any variables, functions or data you might be trying to use in the function. The passed_variable placeholder can be one or more variables that are passed to the function so they can be used. These are known as function arguments, and are how we can move data between one function and another.

!!! hint Understanding how data moves between functions is an important part of programming, as side effects can happen when you don't know what's happening behind the scenes. Make sure you feel solid with the next concepts as they can change depending on the programming language and is the starting point for reducing bugs in code and secure programming.

Passing-by-value and Passing-by-reference

These concepts are two different ways we pass variables to functions in programming. When we pass a value by reference