0% found this document useful (0 votes)
4 views19 pages

Python Study Guide

This document is a comprehensive study guide for Python programming, specifically designed for 5th semester exam preparation. It covers various topics including input/output, control flow, functions, loops, lists, dictionaries, tuples, and sets, along with their respective operations and examples. The guide is structured into units with allocated study hours for each topic.

Uploaded by

shivamjais.op09
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Python Study Guide

This document is a comprehensive study guide for Python programming, specifically designed for 5th semester exam preparation. It covers various topics including input/output, control flow, functions, loops, lists, dictionaries, tuples, and sets, along with their respective operations and examples. The guide is structured into units with allocated study hours for each topic.

Uploaded by

shivamjais.op09
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

■ Python Programming

Complete Study Guide

Paper Code: 153504 | L-3 P-0 C-3

5th Semester Exam Preparation

Unit Topic Hours


1 Input and Output 7 hrs
2 Control Flow, Functions, Loops & Strings 9 hrs
3 Lists 4 hrs
4 Dictionaries, Tuples and Sets 8 hrs
5 Files 7 hrs
6 OOP and Python Modules 7 hrs

Python Programming — 5th Semester Study Guide Page 1


■ 7 hrs
Unit 1.0 — Input and Output
1.1 Identifiers & Keywords
Identifiers are names given to variables, functions, classes, etc. Rules: must start with a letter or
underscore, can contain letters/digits/underscores, case-sensitive, cannot be a keyword.

Category Examples
Keywords (reserved) if, else, elif, while, for, def, class, return, import, True, False, None, and, or, not, in, is, pass, b
Valid Identifiers myVar, _count, student_name, PI, Class1
Invalid Identifiers 2var (starts with digit), my-var (hyphen), class (keyword)

1.2 Variables & Data Types


Python is dynamically typed — you don't declare types. A variable is created when you assign a
value.

# Variable assignment
x = 10 # int
pi = 3.14 # float
name = 'Alice' # str
flag = True # bool
data = None # NoneType
z = 3 + 4j # complex

Data Type Description Example


int Whole numbers 42, -7, 0
float Decimal numbers 3.14, -0.5, 2.0e3
complex Real + imaginary 3+4j
str Text string 'hello', "world"
bool True or False True, False
NoneType Absence of value None

1.3 Operators
Type Operators Example
Arithmetic + - * / // % ** 5//2=2, 2**3=8, 10%3=1
Comparison == != > < >= <= 5>3 → True
Logical and or not True and False → False
Assignment = += -= *= /= //= %= **= x += 5
Bitwise & | ^ ~ << >> 5&3→1
Identity is is not x is None

Python Programming — 5th Semester Study Guide Page 2


Membership in not in 'a' in 'apple' → True

Operator Precedence (high→low): ** → +x -x ~ → * / // % → + - → << >> → & → ^ → | →


comparisons → not → and → or

1.4 Statements & Expressions


An expression evaluates to a value (e.g., 2+3). A statement performs an action (e.g., x=5,
print(x)).

Indentation is mandatory in Python. Use 4 spaces per level. Indentation defines blocks (if-body,
loop-body, function-body).

if True:
print('indented block') # 4 spaces
x = 10
print('back to level 0')

1.5 Comments
# This is a single-line comment
"""
This is a multi-line comment
(also used as docstrings)
"""

1.6 Reading Input & Print Output


name = input('Enter name: ') # always returns str
age = int(input('Age: ')) # convert to int
print('Hello', name) # space-separated
print('Hello', name, sep='-') # custom separator
print('Line 1', end=' ') # no newline
print(f'Name={name}, Age={age}') # f-string
print('Pi = {:.2f}'.format(3.14159)) # format()

1.7 Type Conversions

Python Programming — 5th Semester Study Guide Page 3


int('42') # → 42
float('3.14') # → 3.14
str(100) # → '100'
bool(0) # → False (0, '', [], None are falsy)
list('abc') # → ['a', 'b', 'c']

1.8 type() and is Operator


type(42) #
type('hi') #
isinstance(42, int) # True
x = [1, 2]; y = x
x is y # True (same object in memory)
x is [1,2] # False (different object)

■ Dynamic vs Strong Typing


Python is DYNAMICALLY typed (types resolved at runtime) and STRONGLY typed (no implicit coercion
between unrelated types — '3' + 3 raises TypeError).

Python Programming — 5th Semester Study Guide Page 4


Unit 2.0 — Control Flow, Functions, ■ 9 hrs
Loops & Strings
2.1 if / elif / else
marks = int(input('Marks: '))
if marks >= 90:
print('A grade')
elif marks >= 75:
print('B grade')
elif marks >= 60:
print('C grade')
else:
print('Fail')

Nested if: An if block inside another if block. Useful for multi-condition checks.

2.2 Built-in Functions & Common Modules


Function/Module Purpose Example
len() Length of sequence len([1,2,3]) → 3
range() Generates number sequence range(1,6) → 1,2,3,4,5
abs() Absolute value abs(-5) → 5
max() / min() Max/Min of sequence max([3,1,2]) → 3
sum() Sum of iterable sum([1,2,3]) → 6
round() Round a float round(3.567,2) → 3.57
sorted() Returns sorted list sorted([3,1,2]) → [1,2,3]
math module sqrt, ceil, floor, pi… import math; [Link](16)→4.0
random module Random numbers [Link](1,10)

2.3 Functions
def greet(name, msg='Hello'): # default parameter
"""Greet a person.""" # docstring
return f'{msg}, {name}!'
print(greet('Alice')) # Hello, Alice!
print(greet('Bob', 'Hi')) # Hi, Bob!

Scope & Lifetime: Variables inside a function are local — they exist only during the function call.
Variables outside are global.

Python Programming — 5th Semester Study Guide Page 5


x = 10 # global
def foo():
global x # modify global inside function
x = 20
foo(); print(x) # 20

A function with no return statement returns None implicitly (void-like behaviour).

2.4 while Loop


i = 1
while i <= 5:
print(i, end=' ') # 1 2 3 4 5
i += 1

2.5 for Loop


for i in range(1, 6):
print(i, end=' ') # 1 2 3 4 5
for ch in 'Python':
print(ch, end='-') # P-y-t-h-o-n-

2.6 break, continue, pass


for i in range(10):
if i == 5: break # exit loop
if i % 2 == 0: continue # skip even
print(i, end=' ') # 1 3
def empty(): pass # placeholder

2.7 Strings
s = 'Hello, World!'
print(s[0]) # H (indexing)
print(s[-1]) # ! (negative index)
print(s[0:5]) # Hello (slicing)
print(s[::2]) # Hlo ol! (step)
print(s[::-1]) # !dlroW ,olleH (reverse)

Method Description Example


upper() / lower() Change case 'hello'.upper() → 'HELLO'

Python Programming — 5th Semester Study Guide Page 6


strip() Remove whitespace ' hi '.strip() → 'hi'
split(sep) Split into list 'a,b'.split(',') → ['a','b']
join(iter) Join list to string '-'.join(['a','b']) → 'a-b'
replace(old,new) Replace substring 'cat'.replace('c','b')→'bat'
find(sub) Find index (-1 if absent) 'hello'.find('ll') → 2
startswith() Check prefix 'hi'.startswith('h') → True
count(sub) Count occurrences 'banana'.count('a') → 3
format() String formatting '{} {}'.format('Hi','Bob')

# Formatting strings
name = 'Alice'; age = 21
print(f'Name: {name}, Age: {age}') # f-string (Python 3.6+)
print('Name: %s, Age: %d' % (name, age)) # %-style
print('Name: {}, Age: {}'.format(name, age)) # .format()

Python Programming — 5th Semester Study Guide Page 7


■ 4 hrs
Unit 3.0 — Lists
3.1 Creating & Accessing Lists
A list is an ordered, mutable collection of items (any type). Defined with square brackets.

fruits = ['apple', 'banana', 'cherry']


nums = [1, 2, 3, 4, 5]
mixed = [1, 'hello', 3.14, True]
nested = [[1,2], [3,4]]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(nums[1:4]) # [2, 3, 4]
fruits[1] = 'mango' # mutation

3.2 Basic List Operations


a = [1, 2]; b = [3, 4]
print(a + b) # [1, 2, 3, 4] (concatenation)
print(a * 3) # [1, 2, 1, 2, 1, 2] (repetition)
print(3 in [1,2,3]) # True (membership)
print(len(a)) # 2

3.3 List Methods


Method Description Example
append(x) Add item at end [1,2].append(3) → [1,2,3]
insert(i,x) Insert at position i [1,3].insert(1,2) → [1,2,3]
extend(iter) Append all from iterable [1].extend([2,3]) → [1,2,3]
remove(x) Remove first occurrence [1,2,2].remove(2) → [1,2]
pop([i]) Remove & return item [1,2,3].pop() → 3
index(x) Find index of x [10,20].index(20) → 1
count(x) Count occurrences [1,1,2].count(1) → 2
sort() Sort in-place [3,1,2].sort() → [1,2,3]
reverse() Reverse in-place [1,2,3].reverse()→[3,2,1]
copy() Shallow copy b=[Link]()
clear() Remove all items [Link]() → []

3.4 Built-in Functions on Lists

Python Programming — 5th Semester Study Guide Page 8


lst = [3, 1, 4, 1, 5, 9]
print(len(lst)) # 6
print(max(lst)) # 9
print(min(lst)) # 1
print(sum(lst)) # 23
print(sorted(lst)) # [1,1,3,4,5,9] (new list)
print(list(reversed(lst))) # [9,5,1,4,1,3]
print(enumerate(lst)) # index-value pairs

3.5 del Statement & List Comprehension


lst = [10, 20, 30, 40]
del lst[1] # [10, 30, 40]
del lst[0:2] # [40]
# List comprehension (elegant one-liner)
squares = [x**2 for x in range(1, 6)] # [1,4,9,16,25]
evens = [x for x in range(10) if x%2==0] # [0,2,4,6,8]

■ List vs Tuple
Lists are mutable (can change). Tuples are immutable (cannot change after creation). Use tuples for fixed
data (e.g., coordinates) and lists for collections that grow/shrink.

Python Programming — 5th Semester Study Guide Page 9


Unit 4.0 — Dictionaries, Tuples and ■ 8 hrs
Sets
4.1 Dictionaries
A dictionary stores key-value pairs. Keys must be unique and immutable. Values can be any type.

student = {'name': 'Alice', 'age': 21, 'marks': 95}


# Access
print(student['name']) # Alice
print([Link]('age')) # 21 (safe, no KeyError)
# Modify
student['age'] = 22
student['city'] = 'Delhi' # add new key
del student['marks'] # delete key

Method Description Example


keys() All keys [Link]()
values() All values [Link]()
items() All (key,val) pairs [Link]()
get(k, def) Value or default [Link]('x', 0)
update(d2) Merge another dict [Link]({'a':1})
pop(k) Remove & return value [Link]('name')
popitem() Remove last item [Link]()
setdefault(k,v) Set if key missing [Link]('x',0)
clear() Remove all [Link]()
copy() Shallow copy d2 = [Link]()

# Iterate over a dictionary


for key, val in [Link]():
print(f'{key}: {val}')

4.2 Tuples
A tuple is an ordered, immutable sequence. Defined with parentheses (or just commas).

Python Programming — 5th Semester Study Guide Page 10


point = (10, 20) # tuple
single = (42,) # single-element tuple (comma required!)
coords = 1, 2, 3 # packing without parentheses
x, y, z = coords # unpacking
print(point[0]) # 10
print(len(point)) # 2
a, b = point # tuple unpacking

Tuple Method Description Example


count(x) Count occurrences of x (1,2,2,3).count(2) → 2
index(x) Index of first x (10,20,30).index(20) → 1

Relation between Tuples and Lists: list(tup) converts tuple→list; tuple(lst) converts
list→tuple. Tuples can be used as dict keys (since they're immutable); lists cannot.

zip() function: Combines two (or more) iterables into tuples.

names = ['Alice', 'Bob', 'Carol']


scores = [95, 87, 92]
pairs = list(zip(names, scores))
# [('Alice',95), ('Bob',87), ('Carol',92)]
for name, sc in zip(names, scores):
print(f'{name}: {sc}')

4.3 Sets
A set is an unordered collection of unique elements. Supports mathematical set operations.

s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
empty = set() # NOT {} — that makes a dict!
[Link](5) # {1,2,3,4,5}
[Link](1) # removes 1 (KeyError if absent)
[Link](99) # removes 99 if present, no error

Operation Method / Operator Example Result


Union s1 | s2 or [Link](s2) {1,2,3,4,5,6}
Intersection s1 & s2 or [Link](s2) {3,4}
Difference s1 - s2 or [Link](s2) {1,2}
Symmetric Diff s1 ^ s2 or s1.symmetric_difference(s2) {1,2,5,6}
Subset s1 <= s2 or [Link](s2) True/False
Superset s1 >= s2 or [Link](s2) True/False

Frozen Set: An immutable set created with frozenset([1,2,3]). Can be used as a dictionary
key.

Python Programming — 5th Semester Study Guide Page 11


■ 7 hrs
Unit 5.0 — Files
5.1 Types of Files
File Type Description Extension
Text Files Human-readable characters .txt, .csv, .py, .html
Binary Files Stored as raw bytes .jpg, .mp3, .pdf, .exe
CSV Files Comma-separated values .csv

5.2 Text File Operations


# Writing a text file
with open('[Link]', 'w') as f: # 'w' = write (creates/overwrites)
[Link]('Hello, World!\n')
[Link](['Line 2\n', 'Line 3\n'])
# Reading a text file
with open('[Link]', 'r') as f:
content = [Link]() # entire file as string
# OR
lines = [Link]() # list of lines
# OR
for line in f: # line by line (memory efficient)
print([Link]())
# Append mode
with open('[Link]', 'a') as f:
[Link]('New line\n')

Mode Meaning
'r' Read (default) — error if file doesn't exist
'w' Write — creates new / overwrites
'a' Append — adds to end
'x' Exclusive create — error if exists
'b' Binary mode (combine: 'rb', 'wb')
'+' Read & write (combine: 'r+', 'w+')

5.3 File Methods


Method Description
read(n) Read n characters (or entire file if n omitted)
readline() Read one line
readlines() Read all lines into a list

Python Programming — 5th Semester Study Guide Page 12


write(s) Write string s
writelines(lst) Write list of strings (no auto newline)
seek(pos) Move cursor to position pos
tell() Return current cursor position
close() Close the file (automatic with 'with' block
flush() Flush write buffer to disk

5.4 Binary Files & pickle Module


Use binary mode (rb, wb) for non-text files. The pickle module serialises Python objects to binary.

import pickle
data = {'name': 'Alice', 'scores': [90, 85, 92]}
# Serialise (write)
with open('[Link]', 'wb') as f:
[Link](data, f)
# Deserialise (read)
with open('[Link]', 'rb') as f:
loaded = [Link](f)
print(loaded) # {'name': 'Alice', 'scores': [90, 85, 92]}

5.5 CSV Files


import csv
# Write CSV
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](['Name', 'Age', 'Marks'])
[Link]([['Alice',21,95],['Bob',22,87]])
# Read CSV
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row)

5.6 os and [Link] Modules

Python Programming — 5th Semester Study Guide Page 13


import os
[Link]() # current working directory
[Link]('.') # list files in directory
[Link]('new_folder') # create directory
[Link]('[Link]','[Link]')# rename file
[Link]('[Link]') # delete file
[Link]('[Link]') # True/False
[Link]('[Link]') # is it a file?
[Link]('folder') # is it a directory?
[Link]('dir','[Link]')# platform-safe path
[Link]('/a/b/[Link]')# '[Link]'
[Link]('/a/b/[Link]') # '/a/b'

Python Programming — 5th Semester Study Guide Page 14


Unit 6.0 — Object Oriented Design & ■ 7 hrs
Python Modules
6.1 Programming Paradigms
Paradigm Key Idea Example
Procedural Code as sequence of instructions/functions C, Pascal
Object-Oriented (OOP) Code organised around objects (data + behaviour) Python, Java, C++
Functional Functions as first-class values, no side effects Haskell, Python (partial)

6.2 OOP Core Concepts


Class: Blueprint for objects. Object: Instance of a class. Attribute: Data inside an object. Method:
Function inside a class.

class Student:
college = 'ABC College' # class attribute (shared)
def __init__(self, name, age): # constructor
[Link] = name # instance attribute
[Link] = age
def greet(self):
return f'Hi, I am {[Link]}'
def __str__(self): # string representation
return f'Student({[Link]}, {[Link]})'
s1 = Student('Alice', 21) # create object
print([Link]()) # Hi, I am Alice
print(s1) # Student(Alice, 21)

6.3 Inheritance
Inheritance allows a class (child) to reuse attributes and methods of another class (parent). Supports
code reuse and IS-A relationships.

Python Programming — 5th Semester Study Guide Page 15


class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
return 'Some sound'
class Dog(Animal): # Dog inherits Animal
def speak(self): # override method
return 'Woof!'
class Cat(Animal):
def speak(self):
return 'Meow!'
pets = [Dog('Rex'), Cat('Whiskers')]
for p in pets:
print([Link], '->', [Link]())
# Rex -> Woof! Whiskers -> Meow!

6.4 Polymorphism
Polymorphism means the same method name behaves differently for different classes. Python
achieves this through method overriding and duck typing (if it quacks like a duck, treat it as a
duck).

def make_speak(animal): # works for ANY animal class


print([Link]()) # polymorphic call
make_speak(Dog('Rex')) # Woof!
make_speak(Cat('Lucy')) # Meow!

6.5 Encapsulation & Data Hiding


class BankAccount:
def __init__(self, balance):
self.__balance = balance # private attribute (name mangling)
def deposit(self, amt):
if amt > 0: self.__balance += amt
def get_balance(self):
return self.__balance # controlled access via getter
acc = BankAccount(1000)
[Link](500)
print(acc.get_balance()) # 1500
# print(acc.__balance) # AttributeError — private!

Python Programming — 5th Semester Study Guide Page 16


6.6 Python Modules
A module is a .py file containing definitions. Use import to use it.

import math
from statistics import mean, median, stdev
import random
print([Link](144)) # 12.0
print([Link]) # 3.14159…
print([Link](4.3)) # 5
print([Link](4.7)) # 4
data = [10, 20, 30, 40, 50]
print(mean(data)) # 30.0
print(median(data)) # 30
print(stdev(data)) # 15.81…

6.7 numpy — Numerical Python


NumPy provides the ndarray (N-dimensional array) — much faster than Python lists for maths.

import numpy as np
a = [Link]([1, 2, 3, 4, 5])
print(a * 2) # [2 4 6 8 10] (element-wise)
print([Link]()) # 3.0
print([Link]()) # 15
m = [Link]([[1,2],[3,4]])
print([Link]) # (2, 2)
print(m.T) # transpose
print([Link](m, m)) # matrix multiply
z = [Link]((3,3)) # 3x3 zeros
o = [Link]((2,4)) # 2x4 ones
r = [Link](0,10,2) # [0 2 4 6 8]

6.8 ML Libraries: TensorFlow & Keras (Overview)


TensorFlow is an open-source framework by Google for building machine learning and deep
learning models. Keras is a high-level API that runs on top of TensorFlow, making it easy to build
neural networks.

Concept Description
Tensor Multi-dimensional array — the core data unit in TensorFlow
Model A neural network built from layers
Layer Dense (fully connected), Conv2D, LSTM, etc.
Activation ReLU, Sigmoid, Softmax — introduce non-linearity

Python Programming — 5th Semester Study Guide Page 17


Loss Function Measures error — MSE, CrossEntropy
Optimizer Adam, SGD — updates weights to minimise loss
Epoch One full pass over the training data
Batch Subset of training data processed at once

# Simple Keras model structure (conceptual)


from tensorflow import keras
model = [Link]([
[Link](128, activation='relu', input_shape=(784,)),
[Link](64, activation='relu'),
[Link](10, activation='softmax') # 10 classes
])
[Link](optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# [Link](X_train, y_train, epochs=10)

■ Exam Tip
For Unit 6, focus on: class/object creation, __init__, self, inheritance syntax, method overriding, and
understanding what numpy arrays can do. TensorFlow/Keras — know the key terms and a simple model
structure.

Python Programming — 5th Semester Study Guide Page 18


■ Quick Revision Cheatsheet
Topic Key Syntax / Note
Input name = input('Prompt') → always returns str
Type convert int(), float(), str(), bool(), list(), tuple(), set()
f-string f'Value is {x:.2f}'
if-elif-else No switch in Python — use if/elif chains
for loop for i in range(start, stop, step):
while loop while condition: — remember to update condition!
break/continue break exits loop; continue skips to next iteration
def function def name(params): → return value
Default param def f(x, y=10): — default last
List [1,2,3] — mutable, ordered, allows duplicates
Tuple (1,2,3) — immutable, ordered; (x,) for single
Dict {'k':v} — mutable, key-value, keys unique
Set {1,2,3} — unordered, unique elements; set() for empty
File open with open('[Link]','r') as f: — always use with!
File modes r read, w write, a append, b binary, + both
pickle [Link](obj,f) / [Link](f)
csv [Link] / [Link]
Class class Name: + def __init__(self, ...):
Inheritance class Child(Parent):
super() super().__init__() — call parent constructor
Private self.__attr — name mangling (not truly private)
import import module OR from module import func
numpy array [Link]([…]) — vectorised ops, .shape, .mean(), .dot()

Python Programming — 5th Semester Study Guide Page 19

You might also like