User-defined Functions
Why functions?
A function is a named block of code that does one specific task and runs only when it is called. Instead of writing the same 10 lines in five places, we write them once in a function and call it five times.
Types of functions
Defining and calling a function
def function_name(parameters):
"""optional docstring"""
statements
return value # optionaldef greet():
print('Good morning!')
print('Welcome to Class XI')
greet() # call the function
greet() # call it againThe def line is the function header; the indented lines are the function body. Defining a function does not run it — calling it with greet() does.
Parameters and arguments
def area_rectangle(length, breadth): # parameters
return length * breadth
a = area_rectangle(12, 5) # arguments
print('Area =', a)
print('Two rooms =', area_rectangle(4, 3) + area_rectangle(5, 4))Returning a value
return sends a value back to the caller and ends the function immediately. A function without return gives back None.
def show(x):
print('Value is', x) # no return statement
result = show(10)
print('Function returned', result)Function that prints
- Shows result on screen
- Result cannot be used further
- Returns None
Function that returns
- Gives result back to the caller
- Can be stored, added, printed later
- More useful and reusable
Default and keyword arguments
def simple_interest(p, r=8, t=1): # r and t have default values
return p * r * t / 100
print(simple_interest(5000)) # r=8, t=1
print(simple_interest(5000, 10)) # t=1
print(simple_interest(5000, 10, 3))
print(simple_interest(t=2, p=1000)) # keyword arguments, any order- Positional arguments are matched by position.
- Default arguments are used when a value is not passed (
r=8). - Keyword arguments name the parameter (
t=2, p=1000), so order does not matter.
Returning many values
Python can return several values separated by commas; they come back as a tuple that can be unpacked.
def stats(numbers):
total = sum(numbers)
avg = total / len(numbers)
return total, avg, max(numbers) # returns a tuple
t, a, m = stats([45, 78, 62, 91])
print('Total:', t, 'Average:', a, 'Highest:', m)Flow of execution
Python reads the file top to bottom. When it reaches a def, it only remembers the function. When the function is called, control jumps into the body, runs it, and comes back to the line after the call.
print('1. Start')
def square(x):
print('3. Inside square')
return x * x
print('2. Before calling')
y = square(6)
print('4. Back, y =', y)Passing mutable and immutable arguments
If a function changes a list (mutable) passed to it, the change is visible outside. Re-assigning an int or string inside the function does not affect the caller.
def add_bonus(marks_list, bonus):
for i in range(len(marks_list)):
marks_list[i] += bonus # list is mutable: caller sees change
def change_number(n):
n = n + 100 # int is immutable: caller does not see change
m = [70, 80]
add_bonus(m, 5)
x = 10
change_number(x)
print(m, x)Solved programs
Function returning True/False
def is_prime(n):
if n < 2:
return False
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
return False # return ends the function at once
return True
print([x for x in range(1, 30) if is_prime(x)])One function calling another
def factorial(n):
f = 1
for i in range(2, n + 1):
f *= i
return f
def nCr(n, r): # a function calling another function
return factorial(n) // (factorial(r) * factorial(n - r))
print('5! =', factorial(5))
print('Ways to choose 3 from 7 =', nCr(7, 3))Docstring
def celsius_to_f(c):
"""Convert Celsius to Fahrenheit."""
return c * 9 / 5 + 32
print(celsius_to_f(37))
print(celsius_to_f.__doc__)Summary & practice
def name(params):defines;name(args)calls.returnsends a value back and ends the function; no return → None.- Default and keyword arguments make calls flexible.
- Return several values as a tuple.
Write functions: (1) is_even(n) returning True/False, (2) count_vowels(text), (3) power(base, exp=2), (4) min_max(lst) returning both values. Predict: def f(a, b=3): return a * b → print(f(4), f(4, 5), f(b=2, a=7)).
Answer: 12 20 14
