Python Function Definition and Calling
Python Functions
What is a Function in Python?
A function in Python is a reusable block of code that performs a specific task. Functions help reduce redundancy, increase modularity, and make code easier to maintain.
Python def Keyword - Function Definition
To define a function, use the def keyword, followed by the function name and parentheses ().
Syntax:
def function_name(parameters):
# function body
return value # optional
Example: Define a Simple Function
def greet():
print("Hello, welcome to Python!")
Calling a Function in Python
To execute the function code, simply call the function by its name followed by parentheses.
greet()
Output:
Hello, welcome to Python!
Function with Parameters
Functions can accept inputs called parameters to perform operations dynamically.
def greet_user(name):
print("Hello", name)
Calling:
greet_user("Alice")
Output:
Hello Alice
Function with Return Statement
The return statement sends a result back to the caller.
def add(a, b):
return a + b
result = add(10, 5)
print(result)
Output:
15
Function with Default Parameters
You can provide default values for parameters.
def greet(name="Guest"):
print("Welcome", name)
Calls:
greet("John") # Output: Welcome John
greet() # Output: Welcome Guest
Function with Multiple Return Values
Python allows functions to return multiple values using tuples.
def get_user():
name = "Alice"
age = 25
return name, age
n, a = get_user()
print(n, a)
Output:
Alice 25
Types of Function Arguments
Type | Description | Example |
---|---|---|
Positional | Passed in correct position | add(2, 3) |
Keyword | Passed using key=value format | add(b=3, a=2) |
Default | Uses default if no value is passed | greet(name="Sam") |
Variable Length | Accepts many arguments using *args | def add(*nums): |
Example: Variable-Length Arguments
def add_all(*numbers):
total = sum(numbers)
return total
print(add_all(1, 2, 3, 4)) # Output: 10
Best Practices for Writing Python Functions
- Use meaningful function names - e.g., calculate_area()
- Keep functions small - one task per function
- Use docstrings - describe what the function does
- Avoid side effects - return values instead of printing
- Use default and keyword arguments for flexibility