Methods


Collapse Content

Beta page

Variables and Text discussed how to print specific blocks of text. Often, you'll want to print the same message in multiple locations in your code. While you could copy the same code blocks to multiple locations, this isn't good practice, since it will make your code less organized and harder to maintain.

Instead of duplicating your code, you can organize it with methods. A method is a unit of code that can be called by other code. Putting your code into methods helps keep things organized and lets you call the same code multiple times from different parts of your program.

Create Methods

You've already used many built-in methods yourself, such as print to display text. Now it's time to create your own methods.

  1. Create a method, which you can name errorMessage.
  2. Add a print blocks to it to display an error message, such as "An Error has Occurred. The Universe will now end."
  3. To test out your method, call it.
Video Walk-Through

Bonus: You can now modify your earlier calculator to display an error message for incorrect values. For example, you can display an error message of the tip comes out to less than 0.

Methods that take in Variables

Method are especially useful when they can take in input and do something with it. For example, the print blocks takes in text and displays it. You can create your own method that takes in variables as input and does something with them. Modify your previous method so it takes in custom text and displays both your generic error message and the custom one (all at once). Then Modify your call to the method so it passes in custom text.

Modifying a Method to Take Input

Methods that Return Values

Methods can also return values to the code that called it. For example, let's say we want to change our tip calculator to do something with the tip before it's printed.

To return values, use the method block with return.

Take in two variables for the bill and percent, and then use the same math blocks as before to calculate the tip. Instead of printing the tip, return it to the code that called it.

This code can now do more things with the tip. For example, can you add blocks to calculate the total amount (the bill + the tip) and display this total to the user?

Another piece of code can call the same tip method and do something differently with the result. For example, can you add blocks that calculate the tip, rounds the result up and display this to the user?

Methods let you organize and re-use chunks of code!

Contact Us