Courses / Computer Science XI (HSSC-I) – FBISE Complete SLO-Based Course
3.7 Functions and Problem Decomposition
Unit 3 – Programming Fundamentals · 85 min read · 12 MCQs to check yourself
Functions and variable scope in Python
1. Why functions?
A function is a named block of code that performs one task and can be called many times. Benefits:
- Decomposition: a big problem becomes small, manageable functions.
- Reusability / no duplication: write once, call many times (the DRY principle – Don't Repeat Yourself).
- Easier testing and debugging: each function can be tested separately.
- Readability and teamwork: different programmers write different functions.
Spotting duplication: if you copy-paste similar lines with only the numbers changed, move them into a function with parameters.
2. Defining and calling functions
def greet(name): # definition: name is a parameter
print("Welcome,", name)
greet("Ayesha") # call: "Ayesha" is an argument
greet("Bilal")
Output:
Welcome, Ayesha
Welcome, Bilal
| Term | Meaning |
|---|---|
| Parameter | Variable in the function definition that receives a value |
| Argument | Actual value passed when calling the function |
| Return value | Value sent back to the caller with return |
| Default parameter | Has a value if no argument is given: def power(x, n=2) |
| Keyword argument | Passed by name: power(n=3, x=2) |
3. Types of functions
| Type | Example |
|---|---|
| Built-in functions | print(), len(), input(), int(), max(), range() |
| Library (module) functions | math.sqrt(), random.randint() |
| User-defined functions | functions you write with def |
| Without/with parameters, without/with return value | greet(), area(r), print_line(), square(x) returns |
4. Returning values
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
for c in [0, 37, 100]:
print(c, "C =", celsius_to_fahrenheit(c), "F")
Output:
0 C = 32.0 F
37 C = 98.6 F
100 C = 212.0 F
This also shows invoking a function inside a loop (SLO requirement).
def find_max(a, b):
if a > b:
return a
return b
print(find_max(12, 30), find_max(-4, -9))
Output:
30 -4
5. Model paper long question – area of a circle and a rectangle using functions
import math
def circle_area(r):
return math.pi * r ** 2
def rectangle_area(length, width):
return length * width
r = 7
l, w = 8, 5
print(f"Area of circle: {circle_area(r):.2f}")
print("Area of rectangle:", rectangle_area(l, w))
Output:
Area of circle: 153.94
Area of rectangle: 40
6. Scope of variables – local and global
- A local variable is created inside a function; it exists only while the function runs and cannot be used outside.
- A global variable is created outside all functions; it can be read anywhere. To change it inside a function you must declare
global name.
school = "FG College" # global
def show():
city = "Rawalpindi" # local
print(school, city)
show()
print(school)
# print(city) would give NameError: city is local to show()
Output:
FG College Rawalpindi
FG College
count = 0
def increase():
global count
count += 1
increase(); increase()
print(count)
Output:
2
| Local variable | Global variable |
|---|---|
| Declared inside a function | Declared outside all functions |
| Accessible only inside that function | Accessible throughout the program |
| Created when the function is called, destroyed when it ends | Exists for the whole program run |
| Different functions can use the same name safely | Changing it inside a function needs global |
7. Pass by value
When an immutable value (int, float, str) is passed, the function receives its own copy of the value – changing the parameter does not change the caller's variable. This behaves like pass by value. (Technically Python passes object references; a mutable list can be changed inside a function.)
def add_bonus(marks):
marks = marks + 5 # changes only the local copy
return marks
my_marks = 70
new_marks = add_bonus(my_marks)
print(my_marks, new_marks)
Output:
70 75
8. Decomposing a larger problem – a result card
def total(marks):
return sum(marks)
def percentage(t, max_marks):
return t / max_marks * 100
def grade(p):
if p >= 80: return "A+"
elif p >= 70: return "A"
elif p >= 60: return "B"
elif p >= 50: return "C"
return "F"
def report(name, marks):
t = total(marks)
p = percentage(t, len(marks) * 100)
print(f"{name}: total {t}, {p:.1f}%, grade {grade(p)}")
report("Hira", [88, 76, 91, 69, 80])
report("Saad", [55, 48, 62, 50, 58])
Output:
Hira: total 404, 80.8%, grade A+
Saad: total 273, 54.6%, grade C
Python functions – the only guide you'll need
Short and long questions
1. Compare local and global variables with an example.
Model answer
| Local | Global |
|---|---|
| Declared inside a function | Declared outside all functions |
| Usable only inside that function | Usable throughout the program |
| Exists only while the function runs | Exists for the whole run |
Example: rate = 5 (global) · def tax(p): t = p * rate / 100 (t is local) · return t. Printing t outside the function gives NameError. |
2. Write a Python function findmax() that takes two numbers as input and returns the maximum number.
Model answer
def find_max(a, b):
if a > b:
return a
else:
return b
x = float(input("First number: "))
y = float(input("Second number: "))
print("Maximum:", find_max(x, y))
3. Differentiate between parameters and arguments.
Model answer
Parameters are the variable names listed in a function definition, e.g. def area(l, w) – l and w. Arguments are the actual values passed when calling the function, e.g. area(8, 5) – 8 and 5. Arguments are copied into parameters.
4. Write a function that converts Celsius to Fahrenheit and call it inside a loop for 0, 25, 50 and 100.
Model answer
def to_f(c):
return c * 9 / 5 + 32
for c in [0, 25, 50, 100]:
print(c, "C =", to_f(c), "F")
Output: 32.0, 77.0, 122.0, 212.0 °F.
5. What is meant by pass by value? Explain with an example.
Model answer
In pass by value the function receives a copy of the argument's value, so changing the parameter inside the function does not affect the original variable. For immutable values (int, float, str) Python behaves this way:
def change(x): x = x + 10 · n = 5 · change(n) · print(n) → prints 5 (unchanged).
6. Write a Python program to compute the area of a circle and a rectangle by using functions.
Model answer
import math
def circle_area(r):
return math.pi * r * r
def rectangle_area(length, width):
return length * width
r = float(input("Radius of circle: "))
l = float(input("Length of rectangle: "))
w = float(input("Width of rectangle: "))
print("Area of circle =", round(circle_area(r), 2))
print("Area of rectangle =", rectangle_area(l, w))
Example: r = 7 → 153.94; l = 8, w = 5 → 40.0. Each function solves one sub-problem, takes parameters and returns the result.
7. What is a function? Explain the advantages of functions, types of functions, parameters, return values and scope of variables with examples.
Model answer
A function is a named, reusable block of code that performs a specific task: def name(parameters): … return value.
Advantages: decomposition of large problems; reusability and less duplicated code; easier testing/debugging; readability; teamwork.
Types: built-in (print, len, input), module/library (math.sqrt, random.randint), user-defined (def area(…)).
Parameters and arguments: in def area(l, w) l and w are parameters; in area(8, 5) 8 and 5 are arguments; default parameters (def power(x, n=2)) and keyword arguments are allowed.
Return: return l * w sends the result back; a function without return gives None.
Scope: local variables exist only inside the function; global variables are defined outside and can be read everywhere; global x is required to change a global inside a function.
Example: def c_to_f(c): return c * 9 / 5 + 32 called in a loop for several values.
This lesson ends with a quiz of 12 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: 3.6 Lists: Sequence and Repetition with Collections · Next: 3.8 Debugging: Errors, Testing Functions, Dry Runs and Breakpoints
All lessons in Computer Science XI (HSSC-I) – FBISE Complete SLO-Based Course