Search⌘ K
AI Features

Build Your Own Commands

Explore how to create your own Python functions using the def keyword. Understand how to pass parameters, make reusable commands, and use return values to build organized and flexible programs.

We’ve been using built-in functions like print() and input(). Now it’s our turn to create our reusable commands using functions.

Think of a function like a recipe:

  • It has a name.

  • It can take ingredients (inputs).

  • It does something when you use it.

Built-in vs. user-defined functions

  • Built-in functions are already provided by Python, like print() or len().

  • User-defined functions are ones you create using the def keyword.

Creating your functions lets you:

  • Reuse your code.

  • Organize your program.

  • Make it easier to read and understand.

Writing our first function

You’re about to create a simple function that says hello.

Python
def greet(): # Define a new function
print("Hello!") # What it does
greet() # Call the function

We just created and called our first custom function!

What’s happening here?

  • def starts a function definition.

  • greet is the function name.

  • () means it can take inputs (called parameters).

  • greet() runs the function.

Adding your own input

Now let’s make your function flexible by passing in a name.

Python
def greet(name):
print("Hello,", name)
greet("Ava")
greet("Zane")

Now the function works with any name we give it!

Returning a value

Some functions give something back using the return keyword.

Python
def add(a, b):
return a + b
result = add(5, 3)
print(result)

The return keyword sends a value back. We can store or use it.

Functions can do work and return a value you can use later.

Try this: Create your own fun function

Create your own message function!

Python
def favorite_color(color):
print("My favorite color is", color)
favorite_color("green")
favorite_color("purple")

Try changing the message or the function name to make it your own!