Python Functions – Store and Reuse Your Code

Python Functions Example
Understand the output.

Python functions can be very useful. Python functions store logical steps that can be reused.

The advantage with a function is it can be invoked, rather than having to always retype the lines of code that consist of the function.

The Python reserved word to store a Python function is ‘def’. If you start a line of code with ‘def’, it tells Python to store the function, but to only run it if it is called on later.

Python Functions Examples

def hello():
++++print ‘Hello’
hello()

The first two lines in this example are the Python function. The last line below it invokes the function. The Python function will not execute until it is invoked.

Invoking a Built-In Python Function

A Python function could be built-in, so all you have to do is invoke it.

>>> big = max(‘Hello World’)
>>> print big
w

In the above example, ‘max’ is the built-in Python function. The string inside the parenthesis is called the argument. The argument passes through the function. The ‘max’ function then returns the highest character of a string.

Other common built-in functions are ‘float’, and ‘int’. There are many built-in Python functions. However, A Python function you write yourself is called a user defined function.

A Python Function with Arguments

Look at the following Python function:

def addition(x, y):
++++sum = x + y
++++print sum

 

Now you can invoke the function with two function arguments, as follows:

addition(5, 3)

 

Invoking this function should cause ‘8’ to be printed.

Now look at a slightly modified version of the addition function:

def addition(x, y):
++++sum = x + y
++++return sum

 

Notice the word ‘return’ was used. This gives you a return value, and it terminates the function. However, it does not print the value. You control where it prints, such as:

print addition(1, 2)

 

The number ‘3’ would be printed because that would be the return value.

You will not always need to write a Python function in your program, but if you catch yourself reusing code, it might be best to put that code in a Python function that can simply be invoked when you want to execute it.

Get started with interactive Python practice at Codecademy. You will start with the basics, and quickly ramp up to writing your own functions.

 

Leave a Reply

Your email address will not be published. Required fields are marked *