What is a Function?
A function in Python is like a magic spell —you say a name, and it performs an action! Functions help us organize code, avoid repetition, and make programs easier to read.
Why Use Functions?
- Reuse code instead of writing it multiple times
- Make code cleaner and more readable
- Improve debugging by isolating logic
Defining a Function
To define a function, use the def
keyword, followed by a function name and parentheses ()
.
def greet():
print("Hello, Pythonista!")
Real-life Example:
- Imagine a robot waiter that greets every customer at a restaurant.
def greet_customer():
print("Welcome to Python Café! ")
greet_customer() # Calling the function!
Functions with Parameters
Functions can take inputs (called parameters) to work with different data.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Outputs: Hello, Alice!
greet("Bob") # Outputs: Hello, Bob!
Real-life Example:
- Imagine a ticket machine that prints a personalized welcome message.
def print_ticket(name, movie):
print(f"Here's your ticket, {name}, for {movie}!")
print_ticket("Jake", "Avengers")
print_ticket("Lily", "Inception")
Returning Values
Functions can return a value using the return
keyword.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Outputs: 8
Real-life Example:
- A calculator that adds two numbers for you!
def calculate_total(price, tax):
return price + (price * tax)
bill = calculate_total(100, 0.1) # Adds 10% tax
print(f"Total bill: ${bill}")
Default Parameters
You can set default values for parameters in case they're not provided.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Outputs: Hello, Guest!
greet("Sophia") # Outputs: Hello, Sophia!
Summary
Feature | Description |
---|---|
def |
Used to define a function |
Parameters | Allow functions to take input values |
return |
Sends back a result from a function |
Default Parameters | Provide fallback values if no argument is given |
Now go and create your own Python magic spells with functions!
0 Comments