CSCSEC151: Python Programming (Theory Notes)

Table of Contents

Unit 1: Introduction

Basic Elements

Python code is built from these basic elements:

Variables, L-value, R-value, and Comments

Data Types

Python is dynamically-typed, meaning you don't need to declare a variable's type.

CategoryTypeExampleMutable/Immutable?
Number int 10, -50 Immutable
float 3.14, -0.5 Immutable
complex 3 + 4j Immutable
Boolean bool True, False Immutable
Sequence str (string) "Hello", 'Python' Immutable
list [1, "a", 3.5] Mutable
tuple (1, "a", 3.5) Immutable
None Type NoneType None Immutable
Mapping dict (dictionary) {"key": "value"} Mutable
Set set {1, 2, 3} Mutable

Operators

Expressions, Type Conversion, and I/O

Unit 2: Flow of Control & Strings

Flow of Control

Strings

Unit 3: Lists, Tuples, Sets, Dictionaries & Modules

Lists

Tuples

Set

Dictionary

Python Modules

Unit 4: Functions & Modules

Python Functions

Python Modules and Packages

Unit 5: Files, Exceptions, and Plotting

Python Files

Used to read from and write to files on your disk.

Best Practice (with open): This automatically closes the file for you.

# Writing to a file (overwrites)
with open("output.txt", "w") as f:
    f.write("Hello, file!\n")
    f.write("This is a new line.\n")

# Reading from a file
with open("output.txt", "r") as f:
    content = f.read()print(content)

Modes: "r" (read), "w" (write, overwrites), "a" (append), "r+" (read/write).

Exception Handling

How to handle errors gracefully without crashing the program.

try:
    x = 10 / 0
except ZeroDivisionError:
    print("You cannot divide by zero!")
finally:
    print("This always runs.")

Python Graph Plotting using Matplotlib

Matplotlib is a powerful library for creating static, animated, and interactive visualizations.

Installation: You must first install it: pip install matplotlib

Basic Example (Line Plot):

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [2, 4, 1, 5]

plt.plot(x, y) # Create the line plot
plt.title("Simple Line Plot")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.show() # Display the plot

Other common plots include plt.bar() (bar chart), plt.hist() (histogram), and plt.pie() (pie chart).