Why functions? Built-in, module and user-defined
A function is a named block of code that does one job. Functions save you from writing the same code again and make programs easy to read and fix.
- Built-in functions are always ready:
print(),input(),len(),int(),type(),max(),round(). - Functions in modules: a module is a file of ready code. First
importit.import maththenmath.sqrt(16);from random import randintthenrandint(1, 6). Other modules:statistics(mean, median, mode). - User-defined functions: you make them with
def.
def greet(name):
print('Hello', name)
greet('Asha')The first line is the header (ends with a colon). The indented lines are the body.
Parameters and arguments
A parameter is the name written in the def line. An argument is the actual value sent in the call. In def area(l, b), l and b are parameters. In area(5, 3), 5 and 3 are arguments.
Arguments are also called actual parameters; parameters are called formal parameters.
Positional, keyword and default arguments
Positional arguments
Matched by position: first argument → first parameter. power(2, 3) means base = 2, exp = 3. The number of arguments must match.
Default arguments
A parameter can have a ready value: def power(base, exp=2):. Now power(5) gives 25 and power(5, 3) gives 125. Rule: parameters with defaults must come after those without. def f(a=1, b): is an error.
Keyword (named) arguments
You can name the parameter in the call: power(exp=3, base=2). Order then does not matter. Positional arguments must come before keyword ones in a call.
Returning values
return ends the function and sends a value back to where it was called.
def square(n):
return n * n
ans = square(4) # ans = 16- A function with no
return(a void function) gives backNone. - A function can return many values at once; they come back as a tuple:
return s, p→(s, p). - Lines after
returnin the same block never run.
Flow of execution
Python runs statements from top to bottom. A def block is only read and remembered; its body does not run then. When a call is reached, control jumps to the function body, runs it, and on return (or the end of the body) comes back to the calling line. A function must be defined before the line that calls it runs.
1 def add(a, b): 2 return a + b 3 x = 4 4 y = add(x, 6) 5 print(y)
Order: 1 → 3 → 4 → 1 → 2 → 4 → 5. Output: 10.
Scope: local and global variables
Scope is the part of the program where a name can be used.
- A local variable is created inside a function. It exists only while the function runs and cannot be seen outside.
- A global variable is created outside all functions (at the top level). It can be read inside any function.
- If you assign to a name inside a function, Python makes a new local name, even if a global has the same name.
- To change a global inside a function, write
global xfirst.
x = 10
def f():
x = 5 # new local x
print(x) # 5
f(); print(x) # 10
def g():
global x
x = 99
g(); print(x) # 99Python looks for a name in this order: Local → Enclosing → Global → Built-in (LEGB rule).
Passing a list
If you pass a list and change it inside with append, the caller sees the change (the list is mutable and the same object is shared). Passing an int and doing n += 1 inside does not change the caller's int.
Try it: build a bill machine
Write def bill(price, qty=1, gst=18): that returns the total. Before running, guess the answers of bill(100), bill(100, 3) and bill(100, gst=5). Then run and check. Now add print(price) after the function call outside it and see the NameError: price is local.
Key formulas and definitions
- def name(parameters): body → name(arguments)
- Default parameters come last: def f(a, b=2, c=3)
- No return → returns None; return a, b → returns a tuple
- Name lookup: Local → Enclosing → Global → Built-in (LEGB)
Worked examples
1. Identify the parameters and arguments: def area(l, b): return l*b ... print(area(7, 4))
Parameters: l and b (in the def line). Arguments: 7 and 4 (in the call). Output: 28.
2. def power(base, exp=2): return base ** exp. Find power(3), power(3, 3), power(exp=0, base=9).
power(3): exp uses default 2 → 9. power(3, 3) → 27. power(exp=0, base=9): keyword arguments → 9 ** 0 = 1.
3. Which headers are valid? (a) def f(a, b=1) (b) def f(a=1, b) (c) def f(a=1, b=2)
(a) valid. (b) invalid: a parameter without default cannot follow one with default. (c) valid.
4. Write the flow of execution for: 1 def sq(n): 2 return n*n 3 a = 3 4 print(sq(a) + 1)
1 (def remembered) → 3 → 4 (call) → 1 → 2 (returns 9) → 4 (prints 10).
5. x = 5 def f(): x = 20 print('in', x) f() print('out', x)
Inside f, x = 20 makes a local x. Output: in 20, then out 5. The global x is unchanged.
6. Write a function stats(L) that returns the sum and average of a list. Call it for [4, 8, 6].
def stats(L): s = sum(L) return s, s / len(L) t, a = stats([4, 8, 6]) print(t, a) # 18 6.0
7. c = 0 def inc(): global c c += 1 inc(); inc(); print(c)
global c lets the function change the global c. Two calls add 1 twice. Output: 2. Without global, c += 1 gives UnboundLocalError.
Common mistakes
- Mixing up parameters (in def) and arguments (in the call).
- Putting a default parameter before a non-default one: def f(a=1, b).
- Printing inside a function and expecting a value back; use return to send a value.
- Changing a global inside a function without writing global first (you get a new local or an UnboundLocalError).