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.
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.
Now the function works with any name we give it!
Returning a value
Some functions give something back using the return keyword.
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!
Try changing the message or the function name to make it your own!