Monday, July 25, 2011

Super Simple Python #4 - Defining functions and the return statement

One of the many cool things about Python is the really easy way to define functions. But before we can define any functions, we first need to define "function"! A function is a bit of code that is grouped together to do some task. The print function in the last lesson, for example, outputs stuff to the console. Here's how we define one:

>>> def my_function():
    print('Hello World!')

Make sure you hit enter a couple times until the ">>>" shows up again. You've now defined a function! To use it, type:

>>> my_function()
Hello World!

We can also pass it variables by adding them in the parentheses, separated by commas.

>>> def insult_comeback(insult1, insult2):
    print(insult1)
    print(insult2)
    print("Oh yeah? Well... your mom!")

>>> insult_comeback("Bite me.", "You smell.")
Bite me.
You smell.
Oh yeah? Well... your mom!

Most good functions have a return statement at the end. It does exactly that: returns what's after it to whatever called it. Like so:

>>> def adder(x, y):
    new_number = x + y
    return new_number

>>> adder(2, 3)
5

The good thing about return statements is that they can go into a variable!

>>> eight = adder(3, 5)
>>> eight
8

Putting that all together, we can do nifty stuff like:

>>> def get_a_comeback(what_they_said):
    print("What they said to me: " + what_they_said)
    my_comeback = "Yes, and this one will be if you sit down."
    return my_comeback

>>> my_comeback = get_a_comeback("Is this seat empty?")
What they said to me: Is this seat empty?
>>> print(my_comeback)
Yes, and this one will be if you sit down.

No comments:

Post a Comment