Build Your Own Commands
Understand how to define and use functions with arguments.
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()orlen().User-defined functions are ones you create using the
defkeyword.
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.
def greet(): # Define a new functionprint("Hello!") # What it doesgreet() # Call the function
We just created and called our first custom function!
What’s happening here?
defstarts a function definition.greetis 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.
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.
def add(a, b):return a + bresult = 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!
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!