Stage 6 Teaching Python Tricks
Lesson 6 of 12 +10 XP

Functions: Define it once, use it forever

Writing the same code multiple times is bad practice. In Python, you can package a block of code, give it a name, and then run it whenever you want just by calling that name. This magical package is called a Function.

Sarpanch
If you teach a dog to "Sit", you don't have to explain how to bend their legs every time. You just say "Sit". Functions are how we teach Python new tricks! 🐕

The "def" Keyword

To create a FunctionA reusable block of code that only runs when it is called., you start with the keyword def (short for define). You give the function a name, followed by parentheses (), and a colon :.

Warning: Defining a function doesn't run it! It just creates it. You have to "call" the function later to actually make it do something.

hello_func.py
# 1. Define the function
def say_hello():
    print("Hello!")
    print("How are you?")

# 2. Call the function
say_hello()
say_hello()
2def say_hello():Creates a new function named say_hello. Everything indented below it belongs to the function.
7say_hello()This "calls" the function. Python pauses, jumps up to run the code inside say_hello, and then comes back here. We call it twice!

Giving data to a function

Functions become really powerful when you give them information to work with. These pieces of information are called Arguments or Parameters. You put them inside the parentheses.

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

greet("Sarpanch")
greet("Priya")
1def greet(name):name is a variable that will catch whatever value we pass into the function.
4greet("Sarpanch")"Sarpanch" is passed into the function. Inside the function, name becomes "Sarpanch".

Getting data back from a function

Often, you don't just want a function to print something. You want it to calculate a result and give that result back to you so you can use it in a variable. You do this using the return keyword.

⚠️ return vs print: print() just shows text on the screen for the human. return actually hands data back to the Python program. As soon as a function hits return, the function stops immediately.
def add_numbers(x, y):
    result = x + y
    return result  # Give the answer back!

# Save the returned value into a variable
my_total = add_numbers(5, 10)
print(my_total)  # Prints 15

A function is exactly like a Blender in your kitchen.

Defining the function: Buying the blender and plugging it in. It doesn't do anything yet.
Arguments (Input): Putting strawberries and milk into the top of the blender.
Calling the function: Pressing the "Blend" button.
Return value (Output): Pouring the finished strawberry smoothie out of the blender to drink.

The Function Machine

5, 10 Arguments (Input) def add_numbers(x,y): return x + y The Black Box 15 Return Value (Output)
Data goes in as Arguments. The function does its job inside. The result comes out as a Return Value.

The Chai Function

Panel 1
Sarpanch
"Everyone keeps asking me to make chai. It takes 15 steps! Boil water, add tea, add sugar, add milk..."
Panel 2
Sarpanch
"I'll write a Python function!"

def make_chai(sugar_spoons):
  return "Hot Chai ☕"
Panel 3
Sarpanch
"Now when they want tea, I just run make_chai(2) and go back to sleep. 😎"

Writing Functions

Try calling the pre-written functions, and then create your own!

💡 Challenges:
  1. Call calculate_dog_years() passing in your own age, and print the result.
  2. Write a function called multiply(a, b) that returns a * b. Call it and print the result!

Functions — Done! 🎩

  • Use def to create a function. E.g., def my_func():
  • Defining a function doesn't run it! You have to call it by writing its name followed by parentheses: my_func().
  • Arguments (or parameters) are variables you pass into the function inside the parentheses.
  • return is used to pass a value back out of the function to whoever called it.
  • print() displays text for humans. return gives data to Python. They are different!
Sarpanch victorious
Congratulations! You're officially writing reusable code. You're half way through the entire course! Next up, we learn how to keep our code super organized using Files and Modules. 📁