Python Notes

Satyajit

1. Python Introduction

Python is a high-level, interpreted, general-purpose language known for readability, versatility, and a massive ecosystem.

  • Clean syntax with indentation
  • Used in web, data science, AI, automation
  • Dynamically typed, open source

2. print() Function

print("Hello, World!")
name = "Alice"
print(f"My name is {name}")
  • print() displays output
  • f-strings (Python 3.6+) for formatting
  • \n for newlines

3. Operators

Arithmetic
+, -, *, /, //, %, **
Comparison
==, !=, >, <, >=, <=
Logical
and, or, not
Identity
is, is not
Membership
in, not in
a, b = 10, 3
print(a // b) # 3
print(a ** b) # 1000

4. if-else Statements

age = 18
if age >= 18:
print("Adult")
else:
print("Minor")

# ternary
status = "Adult" if age >= 18 else "Minor"
  • if-elif-else for multiple conditions
  • Nested if supported

5. Lists

Ordered, mutable collection [ ]

fruits = ["apple", "banana"]
fruits.append("orange")
squares = [x**2 for x in range(5)]
  • Indexing, slicing, append(), pop()
  • List comprehension: [x**2 for x in range(10) if x%2==0]

6. Tuples

Ordered, immutable ( )

colors = ("red", "green", "blue")
x, y = (10, 20) # unpacking
  • Faster than lists, can be dictionary keys
  • Return multiple values from functions

7. Sets

Unordered collection of unique elements { }

A = {1,2,3,4}
B = {3,4,5,6}
print(A | B) # union
print(A & B) # intersection

8. Dictionaries

Key-value pairs {key: value}

student = {"name": "John", "age": 20}
print(student.get("name"))
student["grade"] = "A"
  • .keys(), .values(), .items()
  • Dictionary comprehension: {x: x**2 for x in range(5)}

9. Loops

# for loop
for i in range(5):
print(i)

# while
count = 0
while count < 3:
count += 1
  • break, continue
  • enumerate() for index+value

10. Functions

def greet(name):
return f"Hello, {name}"

# lambda
square = lambda x: x**2
  • *args (tuple) and **kwargs (dict)
  • Default parameters, docstrings

11. File Handling

with open("file.txt", "w") as f:
f.write("Hello\n")

with open("file.txt", "r") as f:
content = f.read()
  • Modes: r, w, a, b
  • CSV handling via csv module

12. Core Concepts

  • Variable: named storage location
  • Data types: int, float, str, bool, list, tuple, set, dict
  • Scope: global vs local
  • Exception handling: try-except
  • Module: single .py file, Package: collection of modules

13. Student Management System

Complete example with class, file I/O, and menu.

import os

class StudentManager:
def __init__(self):
self.students = []
self.load_students()

def add_student(self):
name = input("Name: ")
age = int(input("Age: "))
grade = input("Grade: ")
self.students.append({'id': len(self.students)+1, 'name': name, 'age': age, 'grade': grade})

def view_students(self):
for s in self.students:
print(f"{s['id']} {s['name']} {s['age']} {s['grade']}")

def save_students(self):
with open("students.txt", "w") as f:
for s in self.students:
f.write(f"{s['id']},{s['name']},{s['age']},{s['grade']}\n")

def load_students(self):
if os.path.exists("students.txt"):
with open("students.txt") as f:
for line in f:
data = line.strip().split(",")
if len(data)==4:
self.students.append({'id': int(data[0]), 'name': data[1], 'age': int(data[2]), 'grade': data[3]})

def run(self):
while True:
# menu logic omitted for brevity
pass

Full code in notes includes menu, search, delete, and persistence.