Menu Close

Python Functions 

What are functions? Why are they used?

In python, functions are blocks of code that run when references. They are useful for reusing code rather than having to rewrite lines of code repeatedly. There are many built-in functions, such as print() or input(). 

Defining functions

Defining a function in python is very simple, as we use the def keyword to define the statement, then the name of the function followed by parentheses.
The syntax is below: 

def myFunction(): 
    #code 

Indentation 

The code within the function is always indented, as removing the indent  shows the code as outside of the code block.

Parameters 

Often in a function, we like to pass variables into function to use them within the function. This can be helpful for algorithms and operations. To pass in variables, we use parameters. Parameters need to be defined while defining the function itself.
The syntax is below: 

def myFunction(param1, param2): 
    #code 

These parameters can be used within the code, much like any other variable. However, these parameters are unique to the function itself, and they can only be used within the function. 

Likewise, variables outside of the function typically cannot be used within the function. However, there are 2 main workarounds: You can use parameters to pass them in, or you can use the global keyword to access variables outside of the function. 

Below is an example of how to use the global keyword: 

total = 0
def myFunct():
    global total
    total += 1 

In the example above, the variable total is used as a counter for how many times the function has been called. The global keyword is used to allow the variable to be used within the function. 

Return Value

Often, functions need to return a value to be used in an algorithm. This takes the place of an output as the return value may still be needed further in the code. This can be done by using the return keyword.
The syntax is below: 

def myFunc(): 
    return value 

Calling on functions

To call on a python function, use the name of the function and provide all the correct number of parameters. If there are too many or too little parameters, python will throw an error. 

Example 1: 

def myFunc(x, y): 
    print(x * y) 
 
myFunc(2, 5) 

Output : 

10 

The example above shows calling a function 

Example 2 : 

def myFunc(x, y) : 
    return x * y 
 
myVar = myFunc(3, 4) 
print(myVar) 

Output: 

12 

The example above shows how you can set functions as variables as they have return values. The return value of the function becomes the value of the variable, and thus is able to be printed out. 

Posted in Embedded Programming Language, Python, Textbook and Training Project

Related Articles

Leave a Reply

Your email address will not be published.

Leave the field below empty!