Course 3 – Functions and classes

Functions

A function groups together some lines of code, and is defined by two things:

  • Function name – so we can call it
  • Function Parameters – variables that are used inside the function

Let’s see an example:

The function name is show_on_screen, so we know how to call it, and it receives a parameter, which will be called ‘data’ inside our function – so we can do something with it.

Functions are a way of reusing the code. Instead of having 10 lines and copy-paste them many times, we can call the function. If we want/need to modify them, we do it in only one place.

I’ve talked about functions, and I want you to get used to testing your code, so I expect an input-output validation function from you, for each function you’re creating.

What do I mean by that?

A function receives an input, returns an output, and compares them to check if they are equal.

We can then use it as follows:

Object Oriented Programming (OOP)

A class is simply a container for functions and variables which should be grouped together.

Let’s say we have some variables called name and age:

Let’s write a class that defines a human. A human has a name, an age, it’s eating, working, etc.

Looks strange, i know.

The self parameter has to be given to all member functions – it’s the way we can access data variables and functions from inside that class. (see who_am_i function – we used self to get access to myName, myAge).

Basically, we see that we call a function with an object:

The function retrieves the name and age from the specific instance of the SomeName class, which is called ‘instance’.

Homework

Implement a class that perform mathematical operations (+, -, *, /).

For division, validate to not divide by 0.

Functions must receive two parameters which are used to perform the operations.

The class must also contain two variables, and also have some functions that have no parameters, but further calls back the existing functions with the class variables.

Please test the code with input-output functions, like I said above.

You may also like...