Knowlet

CSCSEC151: Python Programming (Theory Notes)

Unit 1: Introduction

Basic Elements

Python code is built from these basic elements:

  • Python Character Set: The set of valid characters, including letters (A-Z, a-z), digits (0-9), and special symbols.
  • Python Tokens: The smallest individual unit in a program.
    • Keyword: Reserved words with special meanings (e.g., if, for, def, True).
    • Identifier: Names given to variables, functions, etc. (e.g., my_var, age).
    • Literal: Constant data values (e.g., 10, "Hello", 3.14).
    • Operator: Symbols that perform operations (e.g., +, =, >).
    • Punctuator: Symbols used to structure the code (e.g., (, ), #, :).

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

  • Variables: A named location in memory used to store data. You create one by assigning a value: age = 25.
  • l-value and r-value:
    • l-value (Locator value): Refers to a memory location. An identifier that can be on the *left-hand side* of an assignment (e.g., the age in age = 25).
    • r-value (Read value): Refers to a data value. An expression that can be on the *right-hand side* of an assignment (e.g., the 25 in age = 25, or age + 1).
  • Comments: Text ignored by the interpreter, used to explain code. In Python, single-line comments start with #.

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
  • Immutable: Cannot be changed after creation (e.g., numbers, strings, tuples).
  • Mutable: Can be changed after creation (e.g., lists, dictionaries, sets).

Operators

  • Arithmetic: +, -, *, / (float division), // (floor division), % (modulus), ** (exponent).
  • Relational: ==, !=, >, <, >=, <=.
  • Logical: and, or, not.
  • Assignment: =
  • Augmented Assignment: +=, -=, *=, etc.
  • Identity: is, is not (Checks if two variables point to the *same* object in memory).
  • Membership: in, not in (Checks if a value is present in a sequence).

Expressions, Type Conversion, and I/O

  • Expression: A combination of values, variables, and operators that evaluates to a single value (e.g., x + 5).
  • Statement: A complete instruction that Python can execute (e.g., x = 5).
  • Type Conversion (Casting):
    • Implicit: Python automatically converts types (e.g., int + float becomes float).
    • Explicit: You force a type change using functions like int(), float(), str().
  • Input/Output:
    • input("Prompt: "): Accepts data from the console. Returns a string.
    • print(...): Displays output to the console.
     name = input("Enter your name: ") age_str = input("Enter your age: ") age = int(age_str) # Explicit conversion print("Hello,", name, "you are", age, "years old.") 

Unit 2: Flow of Control & Strings

Flow of Control

  • Indentation: Python uses indentation (spaces or tabs) to define code blocks, not curly braces {}. This is mandatory.
  • Sequential: Code executes from top to bottom, one line at a time.
  • Conditional (Selection):
    • if: Executes a block if a condition is true.
    • if-else: Executes one block if true, another if false.
    • if-elif-else: A chain of conditions.
       if x > 10: print("Large") elif x > 5: print("Medium") else: print("Small") 
  • Iterative (Loops):
    • for loop: Iterates over a sequence (like a list, string, or range()).
       for i in range(5): # i will be 0, 1, 2, 3, 4 print(i) 
    • while loop: Repeats a block as long as a condition is true.
       count = 0 while count < 5: print(count) count += 1 
    • break: Exits the loop immediately.
    • continue: Skips the rest of the current iteration and moves to the next.

Strings

  • Introduction: An immutable sequence of characters.
  • Operations:
    • + (Concatenation): "Hello" + " " + "World"
    • * (Repetition): "Go" * 3 (produces "GoGoGo")
    • in (Membership): "H" in "Hello" (produces True)
    • Slicing: s[start:end:step]. Very powerful.
       s = "Python" s[0] # 'P' s[1:4] # 'yth' s[:3] # 'Pyt' s[-1] # 'n' (last character) s[::-1] # 'nohtyP' (reverses the string) 
  • Traversing: Use a for loop: for char in my_string: print(char)
  • Built-in Functions/Methods: len(), .upper(), .lower(), .find(), .split(), .strip().

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

Lists

  • Introduction: A mutable (changeable), ordered sequence of elements.
  • Indexing/Slicing: Works just like strings.
  • Operations: +, *, in, len().
  • Methods: .append(item), .insert(index, item), .pop(index), .remove(item), .sort(), .reverse().
  • Nested Lists: Lists within lists (e.g., matrix = [[1,2],[3,4]]).

Tuples

  • Introduction: An immutable (unchangeable), ordered sequence. Defined with parentheses ().
  • Use Case: Use when you want to ensure data is not accidentally changed. They are faster than lists.
  • Operations: Indexing, slicing, concatenation, repetition, len().

Set

  • Introduction: A mutable, unordered collection of unique elements. Defined with curly braces {} (or set() for an empty set).
  • Adding/Removing: .add(item), .remove(item).
  • Set Operations:
    • | (Union): set1 | set2
    • & (Intersection): set1 & set2
    • - (Difference): set1 - set2

Dictionary

  • Introduction: A mutable, unordered collection of key-value pairs. Defined with {}.
  • Accessing: my_dict['key']. Accessing a non-existent key causes an error.
  • Mutability:
    • Add/Modify: my_dict['new_key'] = "new_value"
  • Traversing:
     for key in my_dict: print(key, my_dict[key]) for key, value in my_dict.items(): print(key, value) 
  • Methods: .keys(), .values(), .items(), .get(key) (safe access, returns None if key not found).

Python Modules

  • A module is a Python file (.py) containing functions and variables.
  • import : Imports the whole module. You access members with module.member.
     import math print(math.pi) 
  • from import : Imports a specific member into your namespace.
     from math import pi print(pi) 

Unit 4: Functions & Modules

Python Functions

  • Definition: A reusable block of code, defined with the def keyword.
     def greet(name): print("Hello,", name) 
  • Call: You execute the function by writing its name: greet("Alice").
  • Arguments: Data passed into a function.
    • Default arguments: def greet(name="Guest")
    • Keyword arguments: greet(name="Alice")
  • Pass by Object Reference:
    • If you pass an immutable object (like a string, int), the function cannot change the original.
    • If you pass a mutable object (like a list), the function *can* change the original.
  • Recursion: A function that calls itself. Must have a base case to stop.
    • Advantages: Elegant solution for some problems (e.g., factorial, tree traversal).
    • Disadvantages: Can be slow and consume a lot of memory (risk of "stack overflow").
  • Scope and Lifetime:
    • Local Scope: Variables defined inside a function. Only exist while the function is running.
    • Global Scope: Variables defined outside all functions. Accessible everywhere.

Python Modules and Packages

  • Module: A single .py file.
  • Package: A collection of modules in a directory. The directory must contain a file named __init__.py (can be empty).

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: The block of code that *might* cause an error.
  • except: The block that runs *if* an error occurs. You can catch specific exceptions (e.g., ZeroDivisionError, FileNotFoundError).
  • finally: This block runs *no matter what* (whether an error occurred or not). Used for cleanup.
 try: x = 10 / 0 except ZeroDivisionError: print("You cannot divide by zero!") finally: print("This always runs.") 
  • User-defined Exception: You can create your own exceptions by inheriting from the Exception class.

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).

Did this resource help you study?

Share feedback or report issues to help improve this resource.