Python Functions
Reusable named blocks of code — the foundation of clean, maintainable Python.
Defining and calling
Python
def greet(name):
'''Return a greeting string.'''
return f"Hello, {name}!"
message = greet("Raman")
print(message) # Hello, Raman!
Default arguments
Python
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Raman") # "Hello, Raman!"
greet("Raman", "Hi") # "Hi, Raman!"
greet("Raman", greeting="Hey") # "Hey, Raman!" — keyword argument
*args — variable positional arguments
Python
def add_all(*numbers):
return sum(numbers)
add_all(1, 2) # 3
add_all(1, 2, 3, 4, 5) # 15
# numbers is a tuple inside the function
**kwargs — variable keyword arguments
Python
def print_info(**details):
for key, val in details.items():
print(f"{key}: {val}")
print_info(name="Raman", age=28, city="Bangalore")
# name: Raman
# age: 28
# city: Bangalore
Return multiple values
Python
def min_max(numbers):
return min(numbers), max(numbers) # returns a tuple
lo, hi = min_max([3, 1, 7, 2, 9])
print(lo, hi) # 1 9
Scope
Python
x = "global"
def demo():
x = "local" # different x, local scope
print(x) # "local"
demo()
print(x) # "global" — unchanged
def modify_global():
global x
x = "changed" # modifies the global x
Docstrings
Always write a docstring (the triple-quoted string right after
def) for functions others will use. They appear in help() and editor tooltips.