Function Definition:
def
keyword followed by a function name.
def my_function(parameter1, parameter2):
# Function body
Function Call:
my_function(value1, value2)
Return Statement:
return
keyword.
def add_numbers(a, b):
result = a + b
return result
sum_result = add_numbers(3, 4)
Parameters and Arguments:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Default Parameters:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Outputs: Hello, Guest!
greet("Bob") # Outputs: Hello, Bob!
Scope:
def my_function():
local_variable = 42
print(local_variable) # Raises an error
Global Variables:
global
keyword to access and modify global variables within a function.
global_var = 10
def modify_global():
global global_var
global_var += 5
modify_global()
print(global_var) # Outputs: 15
Docstrings:
def my_function():
"""
This is a docstring that explains what my_function does.
"""
# Function body
Lambda Functions:
lambda
keyword.
add = lambda x, y: x + y
result = add(3, 4) # Result: 7
Recursive Functions:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)