Why Should I Learn About Functions?
What are Functions?
Functions are groupings of code that have their own name. Using this name, you can “call” your function at multiple places inside of a program without having to rewrite the grouping over and over.
Why should I care?
Sometimes, you want to run the same sequence of code multiple times, but not all in a row. A loop won’t work in these cases, so you need another structure in order to avoid having to write the same thing over and over.
I like to compare functions to the chorus of a song. When you look up lyrics, you often won’t find the chorus typed out in full each time it appears. Many times, after the first definition of the chorus you’ll just see the word “Chorus” representing where those lyrics should go and your mind fills in the rest based on the original chorus lines.
Tell me more!
Functions have a form that allow you to do something similar, but not exactly the same, each time. This is accomplished through parameters.
As you can see above, parameters can be added to functions to provide extra information. Using that extra information, you can get different results from the same function.
This program produces three screens in a row
- “Hello Kiki”
- “Hello Tammy”
- “Hello Shawn”
Once you understand the “function” of functions, they become a miracle for your programs. Not only to they reduce the amount of code you need to write, they’re also a great way to keep things tidy and to categorize chunks of code, allowing you to organize your program by area.