Functions
Functions are reusable blocks of code that perform a specific task. They help you avoid repetition, organize your code, and make it easier to read and debug. In Python, you define a function with the `def` keyword.
Defining a Function
Use `def` followed by the function name and parentheses containing parameters.
def greet(name):
print(f"Hello, {name}!")
Calling a Function
Use the function name followed by parentheses with arguments.
greet("Alice") # Hello, Alice!
Return Values
Use the `return` statement to send a value back to the caller. If no `return` is given, the function returns `None`.
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
Parameters and Arguments
- Positional arguments – matched by order.
- Keyword arguments – passed by name.
- Default parameters – have a default value if not provided.
- Arbitrary arguments – `*args` collects extra positional arguments, `**kwargs` collects keyword arguments.
def describe(name, age=18):
print(f"{name} is {age} years old.")
describe("Bob") # Bob is 18 years old.
describe("Alice", age=25) # Alice is 25 years old.
def print_all(*args, **kwargs):
print("Positional:", args)
print("Keyword:", kwargs)
print_all(1, 2, name="Alice", age=30)
Two Minute Drill
- Functions are defined with `def` and contain reusable code.
- Use `return` to output a value.
- Parameters can be positional, keyword, default, or arbitrary (`*args`, `**kwargs`).
- Functions improve readability and maintainability.
Need more clarification?
Drop us an email at career@quipoinfotech.com
