Functions
Reading
Given that you don’t really seem to care too much about these sections I’ll stop them for now. Here is my last one and I’ll make a compiled readings page which lists everything. Here is the last round of some of the things I think are important. No more after this so I’m just dumping everything.
-
Hackers and painters - perhaps my favourite of all time which relates a lot of parts of programming with the act of creative processes and art. It’s a very interesting view that you should definitely read.
-
Why procrastinators procrastinate and part 2 How to beat procrastination
-
[Video] Humans need not apply on automation and the future of tech.
Go through these in your own time. If you care I can give you more interesting and relavant things that are good for you to have gone through.
Why functions
So far, variables, operations, conditionals, loops are honestly enough to get you through programming. You can honestly make pretty much every program with what all that I showed already.
At least, theoretically.
In practice, your code needs to be
-
readable - 10 clear lines are usually better than 100 longer lines
-
composable - i.e. you can break it down into components and use it in a variety of contexts.
-
reuseable - having code that has been written once and now can be dragged over to another context
-
maintainable - programs are always changing, how do you write programs in a way
-
hiding detail - bother programmer with only the level of detail that they need to bother with - like you don’t care how a computer adds two numbers but the fact that it does
You have been using functions already
Whenever you used len(), range(), print() or input() you used them not really
knowing how they worked internally but that they work. Even something simple seeming
like print() has quite a bit of complexity locked with in it. Functions are everywhere
with programming, and now you will learn to write your own functions as well as use the
others people have written.
A simple example
>>> def add(x, y):
... return x + y
...
>>> add(5, 10)
15
Here is a python function that can add two numbers x and y and returns their sum.
Take a moment to stare at the code and try to figure out what it does. Type it out, test out a few things.
There are quite a few terms that go along with functions and are quite a mouthful, don’t worry if you don’t immediately get them
Function signature
The line that has the function name and it’s parameters is called a function signature. If you name a function just write only seeing this line will tell you enough about what a function does.
def add(x, y):
def
It stands for definition. Whenever you want to write your own function you have to start with
def
Function name
These follow the same rules as variables, and for the sake of readability, sanity, and keeping your job name functions in a way that the name says what the function does. Like if a function makes a report from a spreadsheet to email it can be called email_report.
Whenever you use a function in a program you called it using it’s name and () round brackets.
Parameters
Inside the brackets (x, y) are the inputs the function takes to work on. This is what lets it
work with a variety of inputs and be general enough. They are always inbetween brackets and are
separated by commas. To have 5 parameters you can make it (a, b, c, d, e).
Inside the function they work just like any variables in your program. How they get their values is not really that function’s concern it’s some other part of the program to figure out.
Note: once you become more experienced you will learn how to start checking if the function parameters are the correct type and input as you expect and how to throw up the right errors.
If you don’t want any parameters you need to put just empty brackets. Like this:
>>> def hi():
... print("Hi how are you doing?")
...
>>> hi()
Hi how are you doing?
Function body
Just like with if conditions, loops and such we had to use :, then indented lines with 4 spaces and finally an empty line which is standard block syntax. Likewise the same with functions. Here is an example.
print("1")
>>> def example():
... print("2")
... print("3")
... print("4")
...
>>> print("5")
On running example you get:
>>> example()
2
3
4
So basically a function just runs the code inside it’s associated block whenever you call it by name in the program.
return
A lot of beginners don’t quite get this, but this is important. Functions basically represent a module of a program, a small unit a code. The return keyword specifies here is the result I want to giveback to the program. Here this example return x + y tells the program I want to return the results of x + y.
Well why not use print? (actual student question)
- Return you can use the result in within your program like
add(add(1, 2), add(3, 4))is me using the same function to easily add together 4 different functions. - Store it in a variable
sum = add(1, 2)that can be used later. - Or even print it
print("The sum is", add(1, 2)).
If you don’t want to return something, mostly because not every function has something worth returning anyway, just omit it from the function. Here is an example of that:
>>> def display(number):
... print(str(number))
...
>>> display(15)
15
A more complex example
>>> def print_name_n_times(name, n):
... for i in range(n):
... print(name)
...
... return n
...
>>> print_name_n_times("Harsh", 5)
Harsh
Harsh
Harsh
Harsh
Harsh
5
Here I use a for loop to print a name n number of times. See here I can pretty much use
almost any programming construct (the few exceptions that exist will come later). I’m also returning
the value of n to show that as well. This has all the elements I mentioned above. See if you can identifiy
- the function signature line
- the function name
- the parameters - how many? and what are their names
- where the return is happening
Understanding the interactive shell better
Now that you get what returns are and have been looking at the examples. What a shell does is basically shows the return from every single line. This is one of the main reasons why it’s so useful for testing and you don’t even need print() statements to inspect what your function is returning.
An exercise
Remember not too long ago you had to write a program which basically took user input until an empty line was entered. Well here I want a function input_numbers() that collects one number per line until the user enters an empty line. Here is what it looks like in action:
>>> primes = input_numbers()
2
3
5
7
11
>>> primes
[2, 3, 5, 7, 11]
>>> no_numbers = input_numbers()
>>> no_numbers
[]
I got a solution in about 9 lines which was 2 empty lines. So it’s not too complex but this will make you hit all the topics needed.
Hints:
-
use lists for this one. to declare an empty list it’s
example = [], an empty list anywhere in the code is just[] -
appendadds numbers to a list -
int("42")gives back42as an integer.
What next?
More exercises and/or a project. What do you want? I strongly suggest exercises because the concepts may be quite simple but they take a while to truly settle down.
If you wanna learn how to write test cases I can show you simple ones in python.
My first application that I have planned for you is a simple discord chat bot. It will combine the above concepts in interesting ways and if you have any ideas we can have fun with it. After that I want to cover the basics of object oriented programming (classes, inheritance etc.)