>_Code Club
← All exercises

python

Functions

A function is a small machine: you give it something (the parameters), it does some work, and it gives you back an answer with return.

def triple(n):
    return n * 3

print(triple(5))    # 15
print(triple(10))   # 30
  • def means "define a function".
  • The code inside the function is indented (4 spaces). Python uses indentation to know what belongs to the function.
  • return sends the answer back to whoever called the function.

print vs return: print shows something on the screen for humans. return hands a value back to the program so it can keep using it.

Your mission

  1. Write a function double(n) that returns n times 2.
  2. Write a function greet(name) that returns the string Hello, NAME!. For example greet("Sam") returns "Hello, Sam!".
Next exerciseMaking decisions →
Loading the editor…