Functions
Creating reusable code blocks with functions, parameters, and return values.
Defining Functions
- Use 'def' keyword to define a function.
- Functions can take parameters (inputs).
- Use 'return' to send back a value.
- Call function by name with parentheses.
# Simple function
def greet():
print("Hello!")
greet() # Call the function
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice")
# Function with return value
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
Default Parameters
- Set default values for parameters.
- Optional parameters must come after required ones.
- Caller can override default values.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (5^2)
print(power(5, 3)) # 125 (5^3)
Multiple Return Values
- Return multiple values as a tuple.
- Unpack returned values into variables.
- Useful for functions that compute multiple results.
def get_stats(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count
return total, count, average
nums = [10, 20, 30, 40]
total, count, avg = get_stats(nums)
print(f"Total: {total}, Count: {count}, Avg: {avg}")
Lambda Functions
- Small anonymous functions defined with 'lambda'.
- Useful for short, simple operations.
- Often used with map(), filter(), sorted().
# Regular function
def square(x):
return x ** 2
# Lambda equivalent
square = lambda x: x ** 2
print(square(5)) # 25
# With map
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16]
# With filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
Scope
- Local variables exist only inside functions.
- Global variables exist outside functions.
- Use 'global' keyword to modify global variables inside functions.
# Global variable
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1
# Local variable
def calculate():
result = 10 * 5 # Local to this function
return result
print(calculate()) # 50
# print(result) # Error: result not defined