Python/Functions

< Python

Objective

  • Discuss the purpose of functions.
  • Learn how to create a simple function.
  • Understand the use of parameters.
  • Work with "default parameter values".
  • Work with positional arguments.
  • Work with keyword arguments.
  • Use the return statement within a function.
  • Understand the location and abstraction of a function.

Lesson

Functions

A function is a way of reusing a block of code so that it can be used more than once. Functions give the programmer the ability to reduce code redundancy and eliminate hours of wasted work. It also allows the code to be centralized, where one change to the function will effect everything that depends on it. Functions can be used to divide and conquer tasks that would seem otherwise impossible to accomplish!

Creating A Function

To create a function, it must be defined with the def keyword, followed by the function's name, with an empty pair of parentheses, ending with a colon. Functions make up a code block, so you'll need to indent any code that's within the function. Don't forget to indent, otherwise you'll get the pesky "IndentationError".

def hello():
    print("Hello, world!")

The code above assigns and creates the function called hello. It acts much like the the command x=1; both the given examples creates a new variable, hello and x respectively.

Now that you've created the function nothing should visibly happen. To actually invoke or call the function, you'll need to use the function's name followed by the followed by the parentheses like demonstrated in the script below.

def hello():
    print("Hello, world!")

hello()

The output should be:

Hello, world!

Adding the command hello() again will result in the words Hello, world! being displayed twice. This demonstrates a small fraction of the function's uses and abilities.

Function Parameters

At this point, you might be wondering why we need to have those pointless parentheses when we call the function. Wouldn't hello be a lot easier than hello(). Believe it or not, but we can pass arguments to the function when we include them within the parentheses. This allows us to create functions that do things passed on their given arguments. First, the arguments need to be declared when the function is first defined and then we need to call it with an argument.

def square(x):
    print(x**2)

square(2)
square(3)
square(4)

The following output should be:

4
9
16

x now acts like a variable within the function square. You should note that x will only exist within the function. Trying something like the example below will definitely causes a NameError.

def square(x):
    print(x**2)

square(2)
square(3)
square(4)
print(x) # x doesn't exist outside of square!

A function can take multiple arguments, each separated by a comma if more than one exists as demonstrated in the next example.

def somemath(x, y):
    print((x**2)+y)

square(2, 3)
square(3, 2)

The following output should be:

7
11

Default Parameters

Having parameters is great, but it can be repetitive to continue to use them over and over, again. We can define a default value for a parameter by setting its value when you define the parameter. Take the script below for example.

def woof(x=0):
    print(x)

woof(1)
woof()
woof(23)

The output should be:

1
0
23

Did you see the second time we called woof? We didn't give an argument, yet it still printed out 0. If no argument is given, a default is automatically assigned.

Returning A Value

If we wanted to use the value that the square function gives us, we would rewrite it make use of the return command.

>>> def square(x):
... 	return x**2
...

Which can then be used to do such fun things as:

>>> print(square(3))
9

or

>>> print(square(square(3)))
81

or even in statements such as:

>>> 10 + square(2)
14

and

>>> y = square(10)
>>> y
100

Assignments

Completion status: About halfway there. You may help to clarify and expand it.

This article is issued from Wikiversity - version of the Wednesday, October 07, 2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.