Unit 2: Functions and data structures
Python Programming notes · PTU syllabus (UGSEC2507)
On this page
Unit summary
Functions organise code into reusable blocks, and Python's built-in data structures — lists, tuples, dictionaries and sets — make handling collections easy. This unit also covers modules, command-line arguments, lambda functions, assert, mutability, and the Math and NumPy modules.
After this unit you can
- Define functions with default parameters, use lambda and understand scope
- Use command-line arguments, assert and modules
- Use lists, tuples and dictionaries and their methods
- Distinguish mutable and immutable objects and use Math and NumPy
PTU syllabus topics
- Built-in functions
- function definition and call
- scope and lifetime of variables
- default parameters
- command-line arguments
- lambda functions
- assert statement
- importing user-defined modules
- mutable/immutable objects — lists
- tuples
- dictionaries and their built-in functions
- passing them as arguments
- using Math and NumPy modules
List
[1, 2, 3]
Ordered and mutable
Tuple
(1, 2, 3)
Ordered and immutable
Dictionary
{"a": 1}
Key-value pairs; fast lookup
Set
{1, 2, 3}
Unordered, unique items
Topic 1
Functions, scope and lambda
pythondef area(l, b=1): # default parameter
return l * b
print(area(5), area(5, 4)) # 5 20
square = lambda x: x * x # anonymous function
print(square(6)) # 36
count = 0 # global
def increment():
global count # needed to change a global
count += 1- Scope: a variable created inside a function is local and exists only during the call; variables at the top level are global.
- assert checks a condition while debugging:
assert marks >= 0, "Marks cannot be negative". - Command-line arguments:
import sys; print(sys.argv)—sys.argv[0]is the script name. - Modules: a
.pyfile of functions; useimport mymoduleorfrom mymodule import area.
Topic 2
Lists, tuples and dictionaries
List
Yes, ordered
marks = [70, 82, 65]
Tuple
No, ordered
point = (3, 4)
Dictionary
Yes, key-value
student = {"name": "Ana", "roll": 12}
Set
Yes, unique, unordered
{1, 2, 3}
pythonmarks = [70, 82, 65]
marks.append(90); marks.insert(0, 55); marks.remove(65); marks.sort()
print(max(marks), min(marks), sum(marks) / len(marks))
student = {"name": "Ana", "roll": 12}
student["course"] = "BCA"
for k, v in student.items():
print(k, v)Topic 3
Mutable vs immutable objects
- Mutable objects (list, dict, set) can be changed in place; when passed to a function, changes inside the function affect the caller's object.
- Immutable objects (int, float, str, tuple) cannot be changed; "changing" creates a new object.
Example
def add(lst): lst.append(5) — calling add(a) changes list a. def inc(n): n += 1 does not change the caller's integer.
Topic 4
Math and NumPy modules
pythonimport math
print(math.sqrt(16), math.factorial(5), math.pi, math.ceil(4.2))
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
print(a.max(), a.min(), a.mean())
b = a.reshape(2, 3) # 2 rows, 3 columns
print(np.dot([1, 2], [3, 4])) # 11
z = np.zeros((2, 2)); f = np.full((2, 2), 7)NumPy arrays are faster than lists for numerical work and support element-wise operations (a * 2 doubles every element).
Key terms
- Lambda
- A small anonymous function written in one line
- Scope
- The region where a variable can be used
- Module
- A file of Python code that can be imported
- Mutable
- Can be changed in place
- NumPy
- A library for fast numerical arrays
Quick revision
- Default parameters, lambda, global keyword.
- sys.argv holds command-line arguments.
- List mutable; tuple immutable; dict key-value; set unique.
- NumPy: array, reshape, dot, zeros, full, mean.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.What is a lambda function?
- Q2.Differentiate between local and global variables.
- Q3.Differentiate between a list and a tuple.
- Q4.What is the use of assert?
- Q5.What does reshape() do in NumPy?
Long-answer questions
- Q1.Explain functions in Python, including default parameters, scope and lambda functions.
- Q2.Explain lists, tuples and dictionaries with their built-in methods.
- Q3.Explain mutable and immutable objects with examples of passing them to functions.
- Q4.Write NumPy programs to create arrays, find min/max, reshape and compute a dot product.
Stuck on this unit?
Message SBS on WhatsApp for help with Python Programming, or to ask about studying BCA at Synetic.
