Your route · 0 of 17 done
MODULE 00 · PROGRAMMING BASICSStep 5 of 8About 45 min

Functions

By the end of this step you can package steps into a named, reusable function, and you'll have written the heart of your description checker.

A function is a named recipe

You've been using functions already: print(), len(), round(), console.log(). Someone wrote them once; you use them by name. Now you'll write your own.

PythonJavaScript
Define itdef add_tax(price):function addTax(price) {
Hand back a result return price * 1.08 return price * 1.08;
Use ("call") itadd_tax(100)addTax(100)

Three parts:

  • The name (add_tax): what you call it by.
  • Parameters (price): the inputs. Each time you call it, you fill them in: add_tax(100) runs the recipe with price set to 100.
  • return: the result it hands back. Without a return, you get nothing back.

Why bother? Because you write the steps once, give them a clear name, and use them anywhere. When something's wrong, you fix it in one place.

Try it

Python: functions · runs in your browser

Output

Press Run (or Ctrl+Enter) to see the output here.

JavaScript: functions · runs in your browser

Output

Press Run (or Ctrl+Enter) to see the output here.

word_count is the core of the tool you're about to build. Notice it copes with an empty description (""): it returns 0 instead of crashing. JavaScript needs an extra line for that (if (trimmed === "") return 0;): splitting empty text in JavaScript gives you a list with one empty item in it, which would count as 1 word. Little differences like this are why you test the odd cases, not just the normal ones.

Types: a note on what goes in and out

def reading_minutes(words: int) -> float: says: this takes a whole number and gives back a decimal number. Those notes are types. In Python they're optional and nothing checks them while the program runs, but your editor and your AI read them and warn you about mistakes. TypeScript is JavaScript with types added (function readingMinutes(words: number): number). You'll see types throughout the course; they're the contract that says what a piece of code expects.

Your turn

Write a function is_too_short(text) (JavaScript: isTooShort(text)) that returns true when a description has fewer than 20 words. Test it on a short sentence and a long one.

    Next: Reading a file