Functions are a way to encapsulate reusable logic in Python. They allow for modularity and make code easier to read and maintain.
A function is a block of code designed to perform a specific task. Functions are executed only when they are called.
def function_name(parameters):
# Code block
return result
Python provides many built-in functions like print()
, len()
, and type()
.
Functions that you define yourself using the def
keyword.
These are functions created with the lambda
keyword.
To define a function, use the def
keyword followed by the function name and parentheses.
To execute a function, call it by its name followed by parentheses, optionally passing arguments inside the parentheses.
def function_name(parameters):
# Code block
return result
def greet():
print("Hello, World!")
greet() # Output: Hello, World!
Function arguments allow you to pass data into functions. There are several types of function arguments in Python:
The simplest form, where arguments are passed in the same order as the function parameters.
Example:
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 25) # Output: Hello Alice, you are 25 years old.
You can pass arguments in the form key=value
, which allows you to specify values by name, rather than position.
Example:
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=25, name="Bob") # Output: Hello Bob, you are 25 years old.
If an argument has a default value, it’s not mandatory to pass a value for that argument when calling the function.
Example:
def greet(name, age=30):
print(f"Hello {name}, you are {age} years old.")
greet("Charlie") # Output: Hello Charlie, you are 30 years old.
These allow you to pass an arbitrary number of arguments to a function using *args
for non-keyword arguments and **kwargs
for keyword arguments.
Example:
def greet(*names):
for name in names:
print(f"Hello {name}")
greet("Alice", "Bob", "Charlie")
Output:
Hello Alice
Hello Bob
Hello Charlie
def greet(**details):
for key, value in details.items():
print(f"{key}: {value}")
greet(name="Alice", age=25)
Output:
name: Alice
age: 25
The return
statement allows a function to send a result back to the caller.
def square(num):
return num ** 2
result = square(4)
print(result) # Output: 16
Lambda functions are concise, single-expression functions defined using the lambda
keyword.
Lambda functions are small anonymous functions defined using the lambda
keyword. They can have any number of arguments but only one expression.
lambda arguments: expression
square = lambda x: x**2
print(square(4)) # Output: 16
Variables defined inside a function are local to that function and cannot be accessed outside.
def my_function():
x = 10 # Local variable
print(x)
my_function() # Output: 10
print(x) # Error: NameError
Use docstrings to document the purpose of a function. These are defined using triple quotes.
def greet(name):
"""This function greets a person by their name."""
print(f"Hello, {name}!")
greet("Alice")
print(greet.__doc__) # Output: This function greets a person by their name.
Objective: Implement functions to solve problems and practice key concepts.
Write a Function to Calculate Factorial:
Write a function factorial(n)
that calculates the factorial of a number recursively.
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
print(factorial(5)) # Output: 120
Write a Function to Check Prime Numbers:
Write a function is_prime(n)
that returns True
if a number is prime, otherwise False
.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(7)) # Output: True
Create a Function with Default Parameters:
Write a function greet_person(name="Friend")
that prints a greeting.
def greet_person(name="Friend"):
print(f"Hello, {name}!")
greet_person() # Output: Hello, Friend!
greet_person("Alice") # Output: Hello, Alice!
Write a Lambda Function:
Create a lambda function that doubles a number and apply it to a list using map()
.
double = lambda x: x * 2
numbers = [1, 2, 3, 4]
print(list(map(double, numbers))) # Output: [2, 4, 6, 8]