A function is a reusable, named block of code. Defining clear functions is the single biggest step toward writing organised, non-repetitive Python code.
Defining a Function
R Code
def square(x): return x ** 2 print(square(5))
Output
25
Default Arguments
R Code
def greet(name, greeting="Hello"): return f"{greeting}, {name}!" print(greet("Rafi")) print(greet("Meera", greeting="Hi"))
Output
Hello, Rafi! Hi, Meera!
*args and **kwargs
*args collects any number of extra positional arguments into a tuple; **kwargs collects any number of extra keyword arguments into a dictionary.
R Code
def summarise(*args, **kwargs): print("Positional:", args) print("Keyword:", kwargs) summarise(1, 2, 3, name="Rafi", age=23)
Output
Positional: (1, 2, 3)
Keyword: {'name': 'Rafi', 'age': 23}Multiple Return Values
R Code
def min_max(numbers): return min(numbers), max(numbers) low, high = min_max([4, 9, 2, 7]) print(low, high)
Output
2 9
Scope: Local vs Global Variables
R Code
x = 10 # global x def modify(): x = 99 # this x is LOCAL to the function print(x) modify() print(x) # unchanged outside the function
Output
99 10
⚠ Common Mistake
A variable assigned inside a function is local by default and does not affect a same-named variable outside it. To modify a global variable from inside a function, you must explicitly declare global x first - but this pattern is best avoided in favour of returning values instead.Advanced: Recursive Functions
🚀 Advanced Example
A recursive function calls itself, stopping at a base case.R Code
def factorial(n): if n <= 1: return 1 return n * factorial(n - 1) print(factorial(5))
Output
120
Key Points
- def name(args): defines a function; return sends a value back to the caller.
- *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary.
- A function can return multiple values at once as a tuple.
- Variables assigned inside a function are local by default and do not leak into the surrounding code.