Python Functions

Python functions will let you repeat code repeatedly every time you call the function. With Python Functions, you do not have to rewrite lines of code repeatedly. When code is loaded into memory, the function is executed.  When the function completes, it is removed from memory. Below is an example of code that can transform into a Python Function;

n = int(input("Please enter a number: ")
print(f'is {n} even: {n%2==0}\\\')

If you want to repeat the execution of code, you would need to copy it repeatedly.  Python loads the contents of the script in memory. Processing the file line by line which will consume resources on the machine.  Functions make code repetition easy in addition to being less resource-intensive.  They look very similar to what we saw with Python statements, as they start with the def keyword.  Below is an example:

def test_func():
    contents of function

To call a function in a script, we need to call the function name:

test_func()

Functions must return something. This introduces a new return keyword that we can use, comparing return to print:

  • print
    • Prints the data to the screen
    • If we assign a variable to a function that prints, the variable will be type None
  • return
    • When executed, this will exit the function once a return is hit
    • If we assign a variable to a function that returns the result, it gets transferred to the function

Print Example

def is_even():
    n = int(input('Enter a number: '))
    if n % 2 == 0:
       print(f'{n} is even!')
n1 = is_even()

When you run is_even

Enter a number: 4 
4 is even! 
n1 
print(n1) 
None

The function will print to the screen, but the variable is None. All functions must return something, and if there is no return keyword, it will return none since nothing is being returned.

Return example

def is_even():
    n = int(input('Enter a number: '))
    if n % 2 == 0:
        return (f'{n} is even!')
n1 = is_even()

Now, when we run is_even and afterward n1, it will return something every time.

Enter a number: 4 
n1 
'4 is even!'

We can see it returns the output we are expecting it to return.

In the next post, we will dig more into functions, looking at how to pass outside data into them.

For more information on functions, click here.