Learning Sections show
Functions in Python
Functions in Python are reusable blocks of code that perform a specific task. They help in organizing code into manageable sections and avoid repetition. Functions are defined using the def
keyword followed by the function name and parentheses ()
.
Defining a Function
A function is defined using the def
keyword. Here's a simple example of a function that takes a parameter and prints a greeting message:
# Defining a function
def greet(name):
# Function body
print("Hello, " + name + "!")
# Calling the function
greet("Alice") # Output: Hello, Alice!
Return Statement
The return
statement is used to return a value from a function. If no return
statement is used, the function returns None
by default.
# Function with return statement
def add(a, b):
return a + b
# Calling the function
result = add(5, 3)
print(result) # Output: 8
Default Arguments
Functions can have default argument values, which are used if no value is provided when the function is called.
# Function with default arguments
def greet(name, message = "Hello"):
print(message + ", " + name + "!")
# Calling the function
greet("Alice") # Output: Hello, Alice!
greet("Bob", "Good morning") # Output: Good morning, Bob!
Variable-Length Arguments
Functions can accept a variable number of arguments using the *args
and **kwargs
syntax.
# Function with *args
def sum_all(*args):
total = 0
for num in args:
total += num
return total
# Calling the function
result = sum_all(1, 2, 3, 4)
print(result) # Output: 10
# Function with **kwargs
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Calling the function
print_info(name="Alice", age=25, city="Wonderland")
Lambda Functions
Lambda functions are small anonymous functions defined using the lambda
keyword. They are useful for short, throwaway functions.
# Lambda function
square = lambda x: x ** 2
# Using the lambda function
print(square(5)) # Output: 25