A function is a reusable block of code that performs a specific task. Functions help organize code, improve readability, and avoid repetition.
A function is defined using the def
keyword followed by the function name and parentheses ()
.
# Simple function to print a message
def greet():
print("Hello, welcome to Python functions!")
greet()
def greet():
- Defines a function namedgreet
.print(...)
- The function prints a welcome message.greet()
- Calls the function to execute it.
Parameters are variables listed in the function definition, while arguments are values passed to the function when calling it.
def add_numbers(a, b):
return a + b
result1 = add_numbers(5, 10)
result2 = add_numbers(20, 30)
print(result1) # Output: 15
print(result2) # Output: 50
a, b
are parameters.- Values passed (
5, 10
,20, 30
) are arguments. - The function returns the sum of
a
andb
.
A function can return a value using the return
statement.
def multiply(x, y=2):
if not isinstance(x, (int, float)) or not isinstance(y, (int, float)):
return "Invalid input"
return x * y
print(multiply(3, 4)) # Output: 12
print(multiply(5)) # Output: 10 (uses default y=2)
print(multiply("a", 3)) # Output: Invalid input
- If parameters are not numbers, the function returns an error message.
y=2
sets a default value fory
.return x * y
returns the product.
We can accept multiple arguments using *args
(returns a tuple) and **kwargs
(returns a dictionary).
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # Output: 15
print(sum_all(10, 20)) # Output: 30
*args
collects all positional arguments into a tuple and sums them.
def introduce(**kwargs):
for key, value in kwargs.items():
print(f"{key.capitalize()}: {value}")
introduce(name="Alice", age=25, country="USA")
**kwargs
collects all keyword arguments into a dictionary.- The function iterates through the dictionary and prints each key-value pair.
- Functions allow code reuse and modularization.
- Parameters are placeholders, while arguments are actual values passed to functions.
- The return statement allows functions to send back values.
- Default parameter values provide fallback values.
*args
handles multiple positional arguments as a tuple.- **
**kwargs
** handles multiple keyword arguments as a dictionary.