📘 CodingMarble Learn

Functions in Python: Build Your Own Machines

A function is a named block of code that does one job. Python has built-in functions (print, len), functions inside modules (math.sqrt, random.randint) and user-defined functions you write with def. Values sent in a call are arguments; the names that receive them are parameters. Arguments can be positional, keyword or use default values. return sends a value back. Python runs code top to bottom, jumps into a function when it is called and comes back after it. Names made inside a function are local; names made outside are global.

🎬 Step-by-step story

  1. A function is a machine with a name. def makes the machine. Nothing runs until you call it.
  2. Arguments go in through the call. Parameters are the slots that catch them, in order.
  3. A default value fills a slot when no argument is given for it. Defaults must come at the end.
  4. return sends one answer back to the caller. Without return, the function gives back None.
  5. Python reads from the top. At a call it jumps into the function, runs it, then comes back to the same line.
  6. Your turn: names made inside a function live only there (local). Try reading and changing a global name.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

Why does nothing happen when I only write def?

def only builds and names the machine. The body runs when you call it, like add(2, 3).

Are parameters and arguments the same?

No. Parameters are the slot names in the def line. Arguments are the real values sent in the call.

Why is def f(a=1, b) an error?

Arguments fill slots from the left. A slot with no default after one with a default would be unclear, so defaults must be last.

What is the difference between print and return inside a function?

print only shows the value on screen. return hands the value back so you can store or use it: ans = f(3).

Why did my function not change the global variable?

Assigning inside a function makes a new local name. Write global x first to change the outside x.

Where does Python go after a function finishes?

Back to the exact line that called it, and it goes on from there.

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.

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

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.

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)    # 99

Python 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

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

Practice quiz

1. In def f(a, b):, a and b are:
2. What does a function return if it has no return statement?
3. Which header is invalid?
4. math.sqrt() is a:
5. Which keyword lets a function change a variable made outside it?

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What are the types of functions in Python class 12?

Built-in functions (like len), functions in modules (like math.sqrt) and user-defined functions made with def.

What is the difference between local and global variables?

A local variable is made inside a function and exists only there. A global variable is made outside all functions and can be read everywhere.

What is a default argument in Python?

A parameter given a ready value in the def line, like exp=2. If the call gives no value for it, the default is used.

Where this is taught

Canada (Ontario)Grade 11A. Programming Concepts and Skills
RomaniaClasa a IX-aStoring data and organising code in a programming language
RomaniaClasa a IX-aStoring data and organising code in a programming language
RomaniaClasa a IX-aStoring data and organising code in a programming language
RomaniaClasa a XI-aSubprograms
CBSE (India)Class 12Computational Thinking and Programming - 2
England (GCSE, A level)Year 103.2 Programming
South Korea고등학교 3학년Programming
Russia10 классAlgorithms and programming

Learn first

Learn next

Related lessons

All Computer Science lessons