Lesson goal: An introduction to functions

Previous: Divisibility of numbers $<1000$ | Home | Next: Returning values

Sometimes in programming you need to perform the same actions over and over again. Instead or inserting the same lines in your code at each location you need the action performed, it's best to define a "function." Functions are chunks of computer code that do a short, very specific task. They are like little computer programs inside a larger program.

As the computer runs a program (from top to bottom), it will ignore your function definition on face value. That is, when it sees a line starting with the word function, it'll simply skip the entire function and resume with the line following the corrsponding end statement. Functions are only run by the computer when they are explicitly called in the program. Here is how you can define your own function:

function name(input 1,input 2,...)
BODY
end
Move the mouse over a dotted box for more information.

Take a look at the default code below (hit [Reload] on your browser to reset the page if needed). It defines a function called sayhi that takes in a single parameter called name. Inside the function, a single print statement is used to greet the person whose name is given. The totality of the function exists between the function line and the end statement. The function is called (or invoked or run) lower in the code via the sayhi("bill") line. Can you guess what will happen? Try changing the name in between the double quotes to something else.

Now you try. Run and tweak the default code, then look at the examples and study the functions they illustrate.

Type your code here:


See your results here:

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.