In Python, a function is a block of organized, reusable code that performs a single action. Functions provide better modularity and code reusability.
Defining a Function
Use the def
keyword to define a function:
def greet(name):
return f"Hello, {name}!"
Calling a Function
Invoke the function by using its name followed by parentheses:
message = greet("Alice")
print(message) # Output: Hello, Alice!
Function Parameters
Functions can have parameters that act as input variables:
def add(a, b):
return a + b
Default Parameters
You can assign default values to parameters:
def greet(name="Guest"):
return f"Hello, {name}!"
*args and **kwargs
For variable-length arguments:
def func(*args, **kwargs):
print(args)
print(kwargs)
Anonymous Functions (Lambda)
Use lambda
for small anonymous functions:
square = lambda x: x * x
print(square(5)) # Output: 25
Returning Values
Functions can return values using the return
statement:
def multiply(a, b):
return a * b
result = multiply(3, 4)
Scope of Variables
Variables defined inside a function are local to that function.
Conclusion
Functions are fundamental in Python programming, enabling code reuse and better organization. Mastering functions is essential for efficient coding.