Python lesson 9

Basic Functions

Write code once, use it many times. Make your own Python commands!

Define and Call a Function

A function is a reusable block of code. You define it once with def, then call it by name whenever you need it. You can pass values in (called parameters) and get a value back with return!

def greet(name):
print("Hello,", name)

greet("Alex") → Hello, Alex
greet("Sam") → Hello, Sam

def greet(name):
    print("Hello,", name)

greet("Alex")
greet("Sam")

What Comes Back?

def double(n):
    return n * 2

print(double(4) + 1)

Your First Function

Click Run to see a function defined and called twice with different names!

Hint: Click Run! say_hi() is defined once but called twice. Each call uses a different name.

def say_hi(name):
    print("Hi,", name + "!")

say_hi("Alex")
say_hi("Sam")

Function with a Parameter

Run the code, then call greet() with YOUR name as the argument!

Hint: Change "Alex" to your own name and run again. The parameter takes whatever you pass in!

def greet(name):
    print("Hello,", name + "!")

greet("Alex")

Function with Return

Run the code to see a function return a value. Then change the numbers!

Hint: return sends a value back from the function. Change 3 and 4 to your own numbers!

def add(a, b):
    return a + b

result = add(3, 4)
print("Sum:", result)

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.