Python for University Exam – Detailed Theory
Guide
This guide covers the fundamentals of Python, including data structures, operations, conditional
statements, loops, and comprehensions.
1. Basics of Python
Python is a high-level, interpreted programming language used for software development, data
analysis, machine learning, and web development.
1.1 Features of Python
Simple and Readable – Python syntax is like English.
Interpreted Language – Code is executed line-by-line.
Dynamically Typed – No need to declare variable types.
Cross-Platform – Runs on Windows, macOS, and Linux.
1.2 Python Syntax and Variables
Python does not require explicit variable declarations.
Variables store data (numbers, text, lists, etc.).
Indentation is used for blocks of code instead of {} like in C/C++.
Comments (#) are used to explain the code.
Example:
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
2. Python Data Structures and Operations
Python provides built-in data structures to organize and store data efficiently.
2.1 Common Data Structures in Python
Data Structure Description Example
List Ordered, mutable collection [1, 2, 3]
Tuple Ordered, immutable collection (1, 2, 3)
Set Unordered collection of unique elements {1, 2, 3}
Dictionary Key-value pairs for fast lookup {"name": "Alice", "age": 25}
2.2 List Operations
Lists store multiple items and allow modifications.
Common operations:
Accessing elements: list[index]
Adding elements: append(), insert()
Removing elements: remove(), pop()
Sorting: sort()
Example:
numbers = [1, 2, 3, 4, 5]
numbers.append(6) # Adds 6 to the list
numbers.sort() # Sorts the list
2.3 Dictionary Operations
Dictionaries store data in key-value pairs.
Keys must be unique, and values can be modified.
Common operations:
Access values: dict[key]
Add/update keys: dict[key] = value
Delete keys: del dict[key]
Example:
student = {"name": "Alice", "age": 20}
student["grade"] = "A" # Adding a new key-value pair
3. Python Conditional Statements and Loops
3.1 Conditional Statements (if, elif, else)
Used for decision-making in a program.
if checks a condition.
elif is used for multiple conditions.
else executes if none of the conditions are met.
Example:
age = 18
if age >= 18:
print("Eligible to vote")
elif age == 17:
print("Wait one more year")
else:
print("Not eligible")
3.2 Loops in Python
Loops repeat a block of code multiple times.
A. for Loop
Used for iterating over sequences like lists and strings.
range(start, stop, step) is used for looping numbers.
Example:
for i in range(1, 6):
print(i) # Prints 1 to 5
B. while Loop
Runs until a condition becomes false.
Example:
x=1
while x <= 5:
print(x)
x += 1
C. Loop Control Statements
break – Exits the loop early.
continue – Skips the current iteration.
Example:
for i in range(1, 6):
if i == 3:
continue # Skips 3
print(i)
4. List and Dictionary Comprehensions
Comprehensions provide a concise way to create lists and dictionaries.
4.1 List Comprehension
A compact way to create lists using loops.
Syntax: [expression for item in iterable if condition]
Example:
squares = [x**2 for x in range(1, 6)] # Creates a list of squares
Filtering with List Comprehension
even_numbers = [x for x in range(1, 10) if x % 2 == 0]
4.2 Dictionary Comprehension
Similar to list comprehension but for dictionaries.
Syntax: {key: value for item in iterable}
Example:
squared_dict = {x: x**2 for x in range(1, 6)}
5. Example Using All Concepts
This program:
Takes a list of numbers.
Extracts even numbers.
Creates a dictionary of their squares.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# List comprehension to filter even numbers
even_numbers = [x for x in numbers if x % 2 == 0]
# Dictionary comprehension to store squares
squared_dict = {x: x**2 for x in even_numbers}
print("Even Numbers:", even_numbers)
print("Squared Dictionary:", squared_dict)
Output:
Even Numbers: [2, 4, 6, 8]
Squared Dictionary: {2: 4, 4: 16, 6: 36, 8: 64}
Object-Oriented Programming (OOP) & Arrays in
Python – University Exam Guide
This guide covers Object-Oriented Programming (OOP) principles and working with arrays in
Python, including converting lists/tuples to arrays, fixed-size arrays, indexing, slicing, and
iterating.
1. Object-Oriented Programming (OOP) in
Python
1.1 What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm based on objects and classes
that allow modular and reusable code.
1.2 Key Features of OOP
Encapsulation – Hiding data inside a class.
Abstraction – Hiding implementation details from the user.
Inheritance – Reusing existing code.
Polymorphism – Using a single interface for multiple implementations.
1.3 Classes and Objects
A class is a blueprint for creating objects.
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display(self):
print(f"Car: {self.brand}, Model: {self.model}")
# Creating an object
my_car = Car("Toyota", "Corolla")
my_car.display()
Output:
Car: Toyota, Model: Corolla
1.4 Inheritance in OOP
Inheritance allows a child class to use properties of a parent class.
Example:
class Vehicle:
def __init__(self, type):
self.type = type
class Car(Vehicle): # Car inherits from Vehicle
def __init__(self, brand, model):
super().__init__("Car")
self.brand = brand
self.model = model
2. Arrays in Python
2.1 What is an Array?
An array is a collection of items of the same data type stored in contiguous memory locations.
Python provides arrays through the array module or NumPy library.
Why Use Arrays Instead of Lists?
Fixed size (more memory-efficient).
Faster access to elements.
Better performance for large data processing.
2.2 Converting Lists or Tuples to Arrays
Using array Module
import array
# Convert list to array
arr = array.array('i', [1, 2, 3, 4, 5])
print(arr)
Output:
array('i', [1, 2, 3, 4, 5])
'i' represents an integer array.
Using NumPy Arrays (More Efficient)
import numpy as np
# Convert list to NumPy array
arr = np.array([1, 2, 3, 4, 5])
2.3 Fixed-Size Arrays
Python lists are dynamic, but using NumPy, we can create fixed-size arrays.
import numpy as np
arr = np.zeros(5, dtype=int) # Creates an array of size 5 with zeros
print(arr)
Output:
[0 0 0 0 0]
Once an array is created, its size cannot be changed.
3. Indexing, Slicing, and Iterating Through
Arrays
3.1 Indexing in Arrays
Indexing allows accessing specific elements in an array.
arr = [10, 20, 30, 40, 50]
print(arr[0]) # First element (10)
print(arr[-1]) # Last element (50)
3.2 Slicing Arrays
Slicing extracts a portion of an array.
arr = [10, 20, 30, 40, 50]
print(arr[1:4]) # Extracts elements from index 1 to 3
print(arr[:3]) # Extracts first 3 elements
print(arr[::2]) # Extracts every second element
Output:
[20, 30, 40]
[10, 20, 30]
[10, 30, 50]
3.3 Iterating Through Arrays
Using for Loop
arr = [10, 20, 30, 40, 50]
for num in arr:
print(num)
Using while Loop
i=0
while i < len(arr):
print(arr[i])
i += 1
4. Structure and Content of Arrays
4.1 Properties of Arrays
Homogeneous elements – All elements should be of the same type.
Fixed-size allocation – Once defined, memory is allocated.
Faster access – Uses indexing for fast retrieval.
4.2 Storing Multi-Dimensional Data
Python allows 2D and 3D arrays using NumPy.
2D Array Example:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
Output:
[[1 2 3]
[4 5 6]]
5. Example Using All Concepts
Converts a list to an array.
Performs indexing, slicing, and iteration.
Uses NumPy for efficiency.
import numpy as np
# Creating an array from a list
arr = np.array([10, 11, 12, 13, 14, 15])
# Indexing and slicing
print("First element:", arr[0])
print("Last three elements:", arr[-3:])
# Iterating through the array
print("Array elements:")
for num in arr:
print(num)
Output:
First element: 10
Last three elements: [13 14 15]
Array elements:
10
11
12
13
14
15