Functions and Parameter Passing in Python
A function is a reusable block of code that runs when it is called. Functions are defined with def, can take parameters and can return a result. Python offers many flexible ways to pass arguments to a function.
Positional Arguments
Arguments are matched to parameters by their position.
def add(a, b):
return a + b
result = add(10, 52)
print(f"Result of sum = {result}")
Keyword Arguments
You write the parameter name when calling the function, so the order doesn't matter.
def employee(name, age, salary):
print(f"Name = {name} Age = {age} Salary = {salary}")
employee(name="Sudheer Singh", age=23, salary=52362)
employee(age=23, name="Sudheer Singh", salary=52362) # order doesn't matter
Default Parameters
def greet(name, message="Hello"):
print(message, name)
greet("John") # Hello John
greet("Sudheer", "Good Morning") # Good Morning Sudheer
Positional + Keyword Arguments Together
Positional arguments must come before keyword arguments.
def employee1(name, age, city):
print(f"name = {name} age = {age} city = {city}")
employee1("John", age=30, city="Indore")
# employee1(name="John", 30, city="Indore") # SyntaxError: positional argument after keyword argument
*args: Any Number of Positional Arguments
Use *args when you don't know how many values will be passed. Inside the function, args is a tuple.
def add_numbers(*args):
total = 0
for number in args:
total = total + number
print(total)
add_numbers(10)
add_numbers(52, 45)
add_numbers(74, 85, 96)
**kwargs: Any Number of Keyword Arguments
**kwargs collects named arguments into a dictionary.
def employee(**details):
print(details)
employee(name="John", age=45, city="Indore")
# {'name': 'John', 'age': 45, 'city': 'Indore'}
def test(*args, **kwargs):
print("Positional", args)
print("Keywords", kwargs)
test(10, 20, 30, name="John", age=30)
Keyword-Only and Positional-Only Parameters
Parameters after * must be passed by name. Parameters before / must be passed by position.
def employee(name, *, age, city): # age and city are keyword-only
print(name, age, city)
employee("Sudheer", age=56, city="Indore")
def add(a, b, /): # a and b are positional-only
return a + b
print(add(10, 20))
try:
print(add(a=10, b=20))
except Exception as e:
print(f"Getting error in call: {e}")
def employee(emp_id, name, /, *, age, city): # both together
print(emp_id, name, age, city)
employee(23, "Sudheer", age=52, city="Indore")
Mutable vs Immutable Arguments
Python passes a reference to the object. If the object is mutable (list, dict, set), changes made inside the function are visible outside. If it is immutable (int, float, str, tuple, bool), the original value never changes.
def add_employee(employees):
employees.append("Rajesh")
employee_list = ["Ranu", "Raj"]
add_employee(employee_list)
print(employee_list) # ['Ranu', 'Raj', 'Rajesh'] - list was changed
def change_number(number):
number = 100
x = 10
change_number(x)
print(x) # 10 - integers are immutable
def update_employee(employee):
employee["salary"] = 60000
employee = {"name": "John", "age": 30}
update_employee(employee)
print(employee) # {'name': 'John', 'age': 30, 'salary': 60000}
Recursion
A recursive function calls itself. It must have a base case that stops the calls.
def factorial(n):
if n == 0 or n == 1: # base case
return 1
else:
return n * factorial(n - 1)
print(factorial(7)) # 5040