Python- Day 23- FUNCTIONS
You’ll learn the essentials of writing functions in Python.
Functions are named blocks of code that perform specific tasks.
They allow you to avoid repetition by grouping reusable code into callable segments.
Function:
A function is a named block of code designed to perform a single, well-defined task.
When you need to execute the task, you simply “call” the function, which tells Python to run the code inside it.
def greet_user():
print("Hello!")
greet_user() # Output: Hello!
>>
Hello!
Why Use Functions?
Instead of repeating code for the same task multiple times, you can write a function once and call it wherever needed.
Passing Information to Functions:
- Parameters: These are the variables listed inside the parentheses in the function definition.
- Arguments: When calling the function, you provide values for these parameters.
def greet_user(username):
print(f"Hello, {username.title()}!")
greet_user('jesse')
>>
Hello, Jesse!
Types of Arguments:
Positional Arguments:
The simplest way to pass arguments to functions.
The order matters, and Python assigns each argument to the respective parameter by position.
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet('dog', 'Willie')
>>
I have a dog named Willie.
Keyword Arguments:
Arguments passed as name=value
pairs, allowing you to skip worrying about the order.
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet(animal_type='hamster', pet_name='Harry')
>>
I have a hamster named Harry.
Default Values:
You can assign a default value to a parameter in the function definition. If an argument is not provided, Python uses the default value.
def describe_pet(pet_name, animal_type='dog'):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet('Willie')
>>
I have a dog named Willie.
Avoiding Argument Errors:
- Python will raise an error if the number of arguments passed to a function doesn’t match the number of parameters defined.
- Too few arguments: If you don’t provide enough arguments, Python will tell you which parameters are missing.
- Too many arguments: If you provide too many, Python will also raise an error indicating the mismatch.
def describe_pet(pet_name, animal_type='dog'):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet()
# Missing 2 required positional arguments: 'animal_type' and 'pet_name'
Exercises to Practice
Display a Message: Write a function display_message()
that prints what you're learning in this chapter. Call the function to ensure it displays correctly.
def display_message():
print("I am learning how to use functions in Python.")
display_message()
# Output: I am learning how to use functions in Python.
Favorite Book: Write a function favorite_book()
that accepts a parameter title
and prints a message like "One of my favorite books is Alice in Wonderland."
def favorite_book(title):
print(f"One of my favorite books is {title}.")
favorite_book('Alice in Wonderland')
# Output: One of my favorite books is Alice in Wonderland.
Positional vs Keyword Arguments:
- Positional Arguments: Must be in the same order as the parameters in the function definition.
- Keyword Arguments: You explicitly name the argument in the function call, so the order doesn’t matter.
describe_pet('hamster', 'Harry') # Positional
describe_pet(animal_type='hamster', pet_name='Harry') # Keyword
Multiple Function Calls
You can call a function as many times as needed with different arguments. This makes functions highly reusable.
describe_pet('hamster', 'Harry')
describe_pet('dog', 'Willie') # Multiple calls with different data
Functions can be stored in separate files called modules to keep your main program file organized. This is useful for large programs.
Functions are one of the foundational building blocks of Python programming.
They help you break complex tasks into manageable parts, avoid redundancy, and make your code more readable and maintainable.
By mastering functions, you’ll make your programming life easier and your code more efficient..
If you found this guide helpful then do click on 👏 the button.
Follow for more Learning like this 😊
If there’s a specific topic you’re curious about, feel free to drop a personal note or comment. I’m here to help you explore whatever interests you!