Session 3.1 : Functions in Python#
Functions in Python allow you to encapsulate reusable blocks of code, making your programs more modular, readable, and efficient. Here's a comprehensive guide to understanding and using functions:
1. Defining Functions#
Functions are defined using the def
keyword.
Example:#
def greet():
print("Hello, World!")
Calling the Function:#
greet() # Output: Hello, World!
2. Function Parameters#
Functions can take arguments (parameters) to work with dynamic data.
Example: Single Parameter#
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
Example: Multiple Parameters#
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
3. Default Parameters#
You can set default values for parameters. If the caller doesn’t provide a value, the default is used.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Charlie") # Output: Hello, Charlie!
4. Return Statement#
The return
statement sends a value back to the caller.
Example:#
def square(num):
return num * num
result = square(4)
print(result) # Output: 16
Multiple Return Values#
def calculate(a, b):
return a + b, a - b
sum_result, diff_result = calculate(10, 5)
print(sum_result, diff_result) # Output: 15 5
5. Keyword Arguments#
You can pass arguments by name, making the code clearer and flexible in order.
Example:#
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")
introduce(age=25, name="Alice") # Output: My name is Alice and I am 25 years old.
6. Variable-Length Arguments#
Functions can accept varying numbers of arguments using *args
(for positional arguments) and **kwargs
(for keyword arguments).
args
Example:#
def add_all(*numbers):
return sum(numbers)
result = add_all(1, 2, 3, 4)
print(result) # Output: 10
*kwargs
Example:#
def display_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25, city="New York")
# Output:
# name: Alice
# age: 25
# city: New York
7. Lambda Functions#
Lambda functions are anonymous functions defined using the lambda
keyword. They're useful for short, single-use functions.
Syntax:#
lambda arguments: expression
Example:#
square = lambda x: x ** 2
print(square(5)) # Output: 25
Lambda with Multiple Arguments:#
add = lambda x, y: x + y
print(add(3, 7)) # Output: 10
8. Scope of Variables#
- Local Scope: Variables defined inside a function.
- Global Scope: Variables defined outside any function.
Example:#
x = 10 # Global variable
def show():
x = 5 # Local variable
print("Inside function:", x)
show() # Output: Inside function: 5
print("Outside function:", x) # Output: Outside function: 10
Modifying Global Variables:#
x = 10
def modify():
global x
x = 20
modify()
print(x) # Output: 20
9. Function Annotations#
You can add optional annotations to hint at the type of parameters and return value.
Example:#
def greet(name: str) -> str:
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
10. Recursive Functions#
A function can call itself. This is called recursion and is useful for problems like factorial or Fibonacci sequences.
Example: Factorial#
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
11. Decorators#
Decorators are functions that modify other functions. They're used for extending functionality.
Example:#
def decorator(func):
def wrapper():
print("Before the function call")
func()
print("After the function call")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# Before the function call
# Hello!
# After the function call
Practice Problems#
- Create a function to find the maximum of three numbers.
- Write a function that takes a string and returns it reversed.
- Create a recursive function to compute the nth Fibonacci number.
Would you like a detailed explanation of any specific concept?