Learn Python – Part 4: The ins and outs of functions
This month, Darren Yates looks at how to group code together to form code blocks called functions.
One of the key practices when writing code is always looking for ways to make your code more manageable, more readable and more modular. So far, the Python code we’ve written hasn’t been all that long, but even with branching and loops, the code has always been just one big chunk. As your apps become more complex, having a single big chunk of code is a sure-fire way of running into trouble, particularly if you need to make changes or fix bugs. The solution to this in Python is to use what’s called ‘functions’. In Java, they’re called ‘methods’ and, in BASIC, they’re ‘procedures’. Essentially, however, they all pretty much do the same thing — they allow you to create code blocks you can then execute by simply calling the function name.
FUNCTION BASICS
Functions might seem complicated to use, but really, they’re dead-easy — you just need to understand how they work. At the most basic level, you create a function using just one line of code: def functionName(): statement_ 1 statement_ 2 etc.
The ‘def’ line defines the start of a function code block — we’ll get to what the parentheses ‘()’ do in a moment. After that, you just enter in your code statements as before as you wish Python to execute them — the only thing is that each code line in the code block must start with at least one tab-key indent. But to get Python to execute the function, you simply call the function by its name: functionName()
That’s it. Simple. Let’s give it a go. The app ‘func1.py’ is a super-simple function: def helloWorld(): print(‘Hello world,’) print(‘from APC magazine!’) helloWorld()
We start by defining the function called ‘helloWorld’, whose code block includes two print statements. Then the actual app itself is just the line to execute the function, which is simply to call the function’s name ‘helloWorld()’. Now let’s say we want to pass a value (called an ‘argument’) to a function to do something with it. For that, you define the function to have a parameter. Imagine you’re a taxi driver — if you’re going to convey passengers, you need a vehicle that has a seat for each person you convey. These parameter variables are those seats. Here’s an example: def multiply(var1, var2): print(var1, ’x’, var2, ’=’, var1*var2) multiply(7,9) multiply(12,11)