< Prev  |  Home  |  Next >

Python Functions

You’ve used lots of functions in Python already, without even knowing what they are. Here’s a function:

You can use this function to print whatever is between the brackets, without having to know how Python actual makes it happen. Python hides the implementation of printing from you, and just gives you a function called “print” to do what you want.

We can make our own function, by using the def keyword, which stands for “definition”:

You can then use this function whenever you need it, just by typing:

Here’s the complete function with its usage:

Challenge

Create (And then use) a function called “printSquare” to print an ASCII square.

Solution


Or even:

Here’s another function you’ll have used before:

This function is a bit different to “print”, because it also returns whatever the user has typed into the variable called “name”. Getting a function to return a value is easy, you just add the return keyword. Here’s a function to return the sum of 3 and 4 to the user:

“getSum” is a bit better than the earlier “printSquare” function, because we might not always want to print the sum of 3 and 4, and now we have the freedom of what to do with the returned result:

That “getSum” function above can return the sum of 3 and 4, but it’d be better if it could add any values, called arguments that you give to it. For example, in the “input” function, you can tell the function what text to print:

Let’s make our “getSum” function more useful by making it accept two arguments to add together:

So now we know how to use functions, but why do we even need them? Well, now we can define a function once, and use it lots of times. If we define a function with parameters, then we can even use a function lots of times with different values, which will save you a lot of time when you come to write bigger programs. Try and use functions in your programs from now on, wherever your program does something more than once.

Challenge

Take a Python program that you’ve already written, and use functions wherever possible (and anything else you’ve learnt since writing it) to make it more efficient.

< Prev  |  Home  |  Next >