Functions

Functions

In this lesson, we will learn about functions and how to pass arguments and return values. C#, Python, and Js offer functions but differ slightly in how they are created.

Prerequisite

This page assumes you have completed the Coding Intro lesson.

Intro

Functions are blocks of code we create that can be used over and over inside our code. Sometimes they are also referred to as methods. Take Sleep() for example; how would you execute the Sleep() command? Would you just sleep in-place or are there steps you would take? The Sleep() function would contain other tasks involved with preparing to sleep, like BrushTeeth, WashFace, and PutOnPajamas. Executing (also referred to as calling) Sleep() inside our program will automatically run the tasks we have put inside.

Python

def Sleep():
    BrushTeeth()
    WashFace()
    PutOnPajamas()

C#

void Sleep(){
    BrushTeeth();
    WashFace();
    PutOnPajamas();
}

JS

function Sleep(){
    BrushTeeth();
    WashFace();
    PutOnPajamas();
}

Creating a Function

A function can have any name, and you define what it does as you wish. Here is a simple and somewhat useless function that we’ll call MyFunction and have it print two lines.

Python

def MyFunction():
    BrainPad.System.Println("Hello from a function")
    BrainPad.System.Println("Functions are handy")

C#

void MyFunction(){
    BrainPad.System.Println("Hello from a function");
    BrainPad.System.Println("Functions are handy");
}

JS

async function MyFunction(){
    await BrainPad.System.Println("Hello from a function");
    await BrainPad.System.Println("Functions are handy");
}

Ignore the “void” and “def” statements for now. They are covered in Returning a Value later on in this lesson.

Our code above doesn’t do anything yet. It only defines our function to the BrainPad. We now need to CALL the function.


Calling a Function

Both coding languages call a function similarly. Try running the code now to see what happens.

Python

def MyFunction():
    BrainPad.System.Println("Hello from a function")
    BrainPad.System.Println("Functions are handy")

MyFunction()

C#

void MyFunction(){
    BrainPad.System.Println("Hello from a function");
    BrainPad.System.Println("Functions are handy");
}
MyFunction();

JS

async function MyFunction(){
    await BrainPad.System.Println("Hello from a function");
    await BrainPad.System.Println("Functions are handy");
}

await MyFunction();

You’ll notice that calling MyFunction() prints both lines of text. Try adding the MyFunction() call twice at the bottom. Can you guess what will happen?

The example above is just a simple function and does not justify the use of a function. Now here’s an example of a more complex function, a multiplication table for the number 3. Don’t worry too much about how this function works. This is only meant to demonstrate how purposeful functions can be.

Python

def MultiplyTable():
    count = 0
    while count<=10:
        BrainPad.System.Println("> "+ str(count) +" x 3 = " + str (count*3))
        count = count + 1;

MultiplyTable()

C#

void MultiplyTable(){
    var count = 0;
    while(count <= 10){
        BrainPad.System.Println("> "+ count +" x 3 = " + count*3);
        count = count + 1;
    }
}
MultiplyTable();

JS

async function MultiplyTable(){
    var count = 0;
    while(count <= 10){
        await BrainPad.System.Println("> "+ count +" x 3 = " + count*3);
        count = count + 1;
    }
}
await MultiplyTable();

Arguments

Information can be passed into a function. This information is called the argument. For example, we create a function to make a robot move, calling that function Move(). What if we want to specify how fast the robot should go? If we specify Move(50) to result in 50% speed, then 50 in this case is the argument.

You can also have multiple arguments, like a second argument specifying how long the robot should move for in addition to its speed. To move at 50% speed for 3 seconds, add the second argument like so, Move(50, 3). Arguments are completely up to you to define.

Here is a very simple function taking a name as an argument and printing “Hello” followed by that name. Of course, a function is not needed for such a simple task, but this example is used for the sake of explaining arguments.

Python

def SayHello(s):
    BrainPad.System.Println("Hello " + s)

SayHello("Brain")
SayHello("Code")

C#

void SayHello(string s){
   BrainPad.System.Println("Hello " + s);
}

SayHello("Brain");
SayHello("Code");

JS

async function  SayHello(s){
    await BrainPad.System.Println("Hello " + s);
 }
 
 await SayHello("Brain");
 await SayHello("Code");

Back to the multiplication table example from earlier. That example always calculates the table for multiplier 3 with the other factor being less than or equal to 10. With arguments, we can now modify the code to accept any multiplier.

Python

def MultiplyTable(number):
    count = 0
    while count<=10:
        BrainPad.System.Println("> "+ str(count) + " x " + str(number) + " = "+ str(count*number))
        count = count + 1;

MultiplyTable(5)
BrainPad.System.Println("==============")
MultiplyTable(66)

C#

void MultiplyTable(int number){
    var count = 0;
    while(count <= 10){
        BrainPad.System.Println("> " + count+" x "+number+" = " + count*number);
        count = count + 1;
    }
}
MultiplyTable(5);
BrainPad.System.Println("==============");
MultiplyTable(66);

JS

async function MultiplyTable(number){
    var count = 0;
    while(count <= 10){
        await BrainPad.System.Println("> " + count+" x "+number+" = " + count*number);
        count = count + 1;
    }
}
await MultiplyTable(5);
await BrainPad.System.Println("==============");
await MultiplyTable(66);

Because we’ve established what our function MultiplyTable() is supposed to do, we now can completely forget about what is inside and just use it. This is very similar to Print() you have already been using. Print() is simply a function that we created for you to show text on the screen. You do not know how it works internally, but you know its purpose when you do use it.


Returning a Value

Finally, let’s talk about using functions to return a value. This can, for example, be a function that calculates distance.

In C#, we have been using void to indicate that the function does not return a value. Python dynamically selects the variable type and there is no need to tell it what to return. However, def is used to define a function.

Let’s make a function that covers Fahrenheit to Celsius. We’ll call it FtoC(). Since temperature can have a decimal point (temp is 74.6, for example), we will use double as the return type. The needed formula is Celsius = (Fahrenheit – 32) * 5 / 9.

Python

def FtoC(f):
    c = (f - 32) * 5 / 9
    return c

celsius = FtoC(72.4)
BrainPad.System.Println(celsius)

C#

double FtoC(double f){
    var c = (f - 32) * 5 / 9;
    return c;
}

var celsius = FtoC(72.4);
BrainPad.System.Println(celsius.ToString());

JS

function FtoC(f){
    var c = (f - 32) * 5 / 9;
    return c;
}
var celsius = FtoC(72.4);
await BrainPad.System.Println(celsius);

Here is a tip for you: There is no need to use a variable to contain the return value. We can simply use the return value immediately.

Python

def FtoC(f):
    c = (f - 32) * 5 / 9
    return c


BrainPad.System.Println(FtoC(72.4))

C#

double FtoC(double f){
    var c = (f - 32) * 5 / 9;
    return c;
}

BrainPad.System.Println(FtoC(72.4).ToString());

JS

function FtoC(f){
    var c = (f - 32) * 5 / 9;
    return c;
}
await BrainPad.System.Println(FtoC(72.4));

What’s Next?

Trying creating more than one function. Try calling a function from inside another function. Because functions can contain multiple arguments, try creating a function that has several arguments. From here you can start learning about all of the functions that are built-in functions.


BrainStorm

Can you explain why using functions might be useful when coding? Can you think of other ways to use functions?

Content Licensing
Newsletter

Twitter Feed
Hot off the press!