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

Cognizant Python Coding Master Book

The 'Python Coding Master Book' is designed to cover the complete syllabus of Python coding from the Cognizant Skill Cluster 2, including explanations, syntax, and practice questions. It is structured into chapters that address various topics such as syntax, loops, strings, data structures, functions, object-oriented programming, and file handling. The book is tailored for a comprehensive learning experience, providing worked programs, output tracing, and timed mock assessments.

Uploaded by

blackweb1432
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 views55 pages

Cognizant Python Coding Master Book

The 'Python Coding Master Book' is designed to cover the complete syllabus of Python coding from the Cognizant Skill Cluster 2, including explanations, syntax, and practice questions. It is structured into chapters that address various topics such as syntax, loops, strings, data structures, functions, object-oriented programming, and file handling. The book is tailored for a comprehensive learning experience, providing worked programs, output tracing, and timed mock assessments.

Uploaded by

blackweb1432
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

COGNIZANT SKILL CLUSTER 2

Python Coding Master Book


Complete syllabus from fundamentals to advanced coding patterns

Explanations | Syntax | Worked programs | Output tracing

Practice questions | MCQs | Solutions | Timed mock

Python 3 | Maximum 60-page assessment-focused edition

Prepared for Shiva

Purpose of this book


This book covers every Python Coding topic from the Cognizant Skill Cluster 2 syllabus. Read the explanation,
type the example, change one input, solve the practice task and record mistakes. Examples use standard
Python 3 syntax.
Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Contents
How to use this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

Suggested five-day use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

Chapter 1: Syntax and Python basics . . . . . . . . . . . . . . . . . . . . . . . . .6

1.1 Syntax, indentation and comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.2 Variables, names, keywords and identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

1.3 Input, output and type conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7

1.4 Built-in data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

1.5 Mutable and immutable objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

1.6 Operators and precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9

1.7 Truthy and falsy values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Chapter 2: Conditional statements and loops . . . . . . . . . . . . . . . . . . . . . 10

2.1 if, elif and else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.2 Nested conditions and conditional expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.3 for loops and range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.4 while loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.5 break, continue, pass and loop else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2.6 enumerate and zip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2.7 Nested loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Chapter 3: Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

3.1 Creating, indexing and slicing strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

3.2 Immutability, comparison and concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

3.3 Essential string methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

3.4 Formatting and f-strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

3.5 Palindrome and anagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3.6 Character frequency and first non-repeating character . . . . . . . . . . . . . . . . . . . . . . . . 15

3.7 Reversing words and longest unique substring . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Chapter 4: Lists, tuples, sets and dictionaries . . . . . . . . . . . . . . . . . . . . 17

4.1 Lists: creation, access and methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

4.2 List slicing, sorting and comprehension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

4.3 Nested lists and matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

4.4 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

4.5 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

4.6 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

4.7 Frequency maps, nested dictionaries and merging . . . . . . . . . . . . . . . . . . . . . . . . . . 20

4.8 Stack, queue, Counter, defaultdict and heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

4.9 Collection complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Chapter 5: Functions and scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

5.1 Defining, calling and returning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

Python Coding Master Book Page 2


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

5.2 Positional, keyword and default arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

5.3 *args and **kwargs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

5.4 LEGB scope, global and nonlocal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

5.5 Lambda and higher-order functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

5.6 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

5.7 Mutable arguments and default-argument trap . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

5.8 Generators and decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Chapter 6: Object-oriented programming . . . . . . . . . . . . . . . . . . . . . . . 26

6.1 Classes, objects, self and __init__ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

6.2 Instance and class variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

6.3 Instance, class and static methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

6.4 Encapsulation and properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

6.5 Inheritance and super . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

6.6 Overriding and polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

6.7 Abstraction and abstract classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

6.8 Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

6.9 Magic methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

6.10 Mini OOP program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

Chapter 7: File handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

7.1 Opening files and modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

7.2 read, readline, readlines, write and writelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

7.3 Counting lines, words and characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

7.4 CSV and JSON files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

7.5 Paths and missing files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

Chapter 8: Modules, packages and important libraries . . . . . . . . . . . . . . . . 36

8.1 Import forms and aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

8.2 Custom modules, packages and main guard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

8.3 math, random, datetime and statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

8.4 collections, itertools and functools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

8.5 json, csv, os and pathlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

Chapter 9: Exception handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

9.1 Syntax errors and runtime exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

9.2 try, except, else and finally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

9.3 raise and custom exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

9.4 Exception best practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

Chapter 10: Important coding patterns . . . . . . . . . . . . . . . . . . . . . . . . 41

10.1 Time and space complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

10.2 Frequency counting and duplicate removal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

10.3 Second largest and missing number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

10.4 Two-sum and dictionary lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

Python Coding Master Book Page 3


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

10.5 Two pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

10.6 Sliding window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

10.7 Prefix sums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

10.8 Sorting with key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

10.9 Stack and queue problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

10.10 Matrix traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

10.11 Basic recursion and memoisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

10.12 Edge-case checklist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Chapter 11: Practice workbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

11.1 Foundation problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

11.2 String problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

11.3 Collection and function problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

11.4 OOP, file and exception problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

Chapter 12: Python MCQ and output practice . . . . . . . . . . . . . . . . . . . . . 49

12.2 MCQ answer key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Chapter 13: Final timed coding mock . . . . . . . . . . . . . . . . . . . . . . . . . 53

13.1 Coding questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

13.2 Testing checklist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

13.3 Model solution patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

Chapter 14: Last-minute revision sheets . . . . . . . . . . . . . . . . . . . . . . . 55

14.1 Syntax and collection cheat sheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

14.2 High-frequency traps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

14.3 Final submission checklist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Python Coding Master Book Page 4


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

How to use this book


The best sequence is concept, typed example, dry run, independent solution and next-day
reattempt. Do not only read programs. Typing exposes indentation, syntax and input-output
mistakes that passive reading hides.

Step Action Target

Learn Read one section and underline the exact rule. Understand definition and purpose.

Type Run the example without copying line by line. Build syntax memory.

Change Modify one value, condition or data structure. Predict output before running.

Solve Attempt the practice question under a timer. Convert knowledge into coding speed.

Review Write the mistake, rule and corrected example. Prevent repeated errors.

Suggested five-day use


Day Main chapters Minimum output

1 Foundations, conditions and loops 15 output traces and 6 programs

2 Strings and core data structures 12 programs

3 Functions and OOP 10 programs and 20 MCQs

4 Files, modules and exceptions 8 programs and 20 MCQs

5 Coding patterns and timed mock One complete mock plus error review

Assessment habit
Before submitting code, confirm the required function name, input format, output format, indentation and
edge cases. Test one normal case and one boundary case.

Python Coding Master Book Page 5


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 1: Syntax and Python basics


This chapter builds the rules needed for every later program: indentation, names, input, types,
objects, operators and truth-value testing.

1.1 Syntax, indentation and comments


Python uses indentation to define a block. The usual convention is four spaces per level. Statements
at the same indentation belong to the same block. Mixing tabs and spaces can create errors or
misleading structure.

Correct indentation

age = 20

if age >= 18:


print("eligible")
print("adult block")

print("program finished")

Item Rule Example

Single-line comment Starts with # and continues to line end. # calculate total

Docstring Triple-quoted text as first statement in """Return the total."""


module/class/function.

Statement Usually one logical instruction per line. total = price * quantity

Continuation Parentheses allow expressions across lines. total = (first + second)

Block Begins after a colon and is indented. if condition:

Common mistake
A comment explains why or a non-obvious decision. Do not fill code with comments that only repeat each
line. In an assessment, indentation is part of correctness.

Python Coding Master Book Page 6


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

1.2 Variables, names, keywords and identifiers


A variable is a name bound to an object. A valid identifier starts with a letter or underscore, contains
letters, digits or underscores, is case-sensitive and cannot be a reserved keyword.

Valid Invalid Reason

student_name 2name An identifier cannot begin with a digit.

total2 total-price Hyphen is subtraction, not part of a name.

_count class class is a keyword.

marks student name Spaces are not allowed.

score Score Both are valid but refer to different names.

Multiple assignment and unpacking

x, y = 10, 20
x, y = y, x

first, *middle, last = [1, 2, 3, 4]


print(x, y)
print(first, middle, last)

Use snake_case for variables and functions, PascalCase for classes and UPPER_CASE for constants
by convention. Choose descriptive names such as total_marks instead of tm.

1.3 Input, output and type conversion


input() always returns a string. Convert it when a program needs numeric operations. print() accepts
several values, a separator and an ending string.

Reading and printing values

name = input().strip()
age = int(input())
height = float(input())

print("Name:", name)
print("Age and height:", age, height, sep=" | ")
print("eligible" if age >= 18 else "not eligible")

Conversion Purpose Possible problem

int(text) Whole-number conversion. ValueError for '12.5' or non-numeric text.

float(text) Decimal conversion. ValueError for invalid text.

str(value) Text representation. Formatting may still need control.

bool(value) Truth-value conversion. bool('False') is True because the string is


non-empty.

list(iterable) Create a list from an iterable. Characters become separate items for a string.

Python Coding Master Book Page 7


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

1.4 Built-in data types


Type Example Mutable? Use

int 25, -7 No Whole numbers

float 3.14, -0.5 No Decimal numbers

bool True, False No Logical state

str 'python' No Text sequence

list [1, 2] Yes Ordered dynamic collection

tuple (1, 2) No Fixed ordered record

set {1, 2} Yes Unique values

dict {'a': 1} Yes Key-value mapping

NoneType None No Absence of a value

Python is dynamically typed because a name can later refer to a different type. It is strongly typed
because unrelated types are not silently combined. For example, '5' + 2 raises TypeError.

Inspecting types

value = 10
print(type(value))

value = "ten"
print(type(value))

nothing = None
print(nothing is None)

1.5 Mutable and immutable objects


Mutable objects can change in place. Immutable objects cannot; an apparent change creates a new
object. Lists, sets and dictionaries are mutable. Integers, floats, booleans, strings and tuples are
immutable.

Mutation and rebinding

a = [1, 2]
b = a
[Link](3)
print(a) # [1, 2, 3]

text = "py"
alias = text
text += "thon"
print(alias) # py
print(text) # python

A shallow copy creates a new outer list but shares nested objects. [Link] creates
independent nested copies when supported.

Shallow and deep copy

import copy

original = [[1], [2]]


shallow = [Link]()
deep = [Link](original)

shallow[0].append(9)
print(original) # [[1, 9], [2]]

deep[1].append(8)
print(original) # still [[1, 9], [2]]

Python Coding Master Book Page 8


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

1.6 Operators and precedence


Family Operators Important point

Arithmetic + - * / // % ** / returns float; // floors; ** is power.

Comparison == != < <= > >= Comparisons return bool and can be chained.

Logical not, and, or and/or short-circuit and return an operand.

Assignment = += -= *= /= //= %= **= Combined assignment updates a name.

Membership in, not in Dictionary membership tests keys.

Identity is, is not Use is None; do not replace == with is.

Operator behaviour

print(7 / 2) # 3.5
print(7 // 2) # 3
print(-7 // 2) # -4, floor toward negative infinity
print(7 % 2) # 1
print(2 ** 3) # 8

x = 5
print(1 < x <= 10)

A safe simplified precedence order is: parentheses, exponentiation, unary signs,


multiplication/division/floor/modulo, addition/subtraction, comparisons, not, and, or. Use
parentheses when an expression may be misread.

1.7 Truthy and falsy values


False, None, numeric zero and empty strings or containers are falsy. Most other values are truthy.
This lets code check if a collection has content without comparing its length to zero.

Truth-value checks

items = []
name = ""

if not items:
print("no items")

if name:
print("name supplied")
else:
print("name missing")

print(bool("False")) # True: non-empty string

Chapter 1 practice
1. Read name, age and percentage and print a formatted eligibility message.
2. Predict ten mixed-operator expressions before running them.
3. Create one mutable and one immutable aliasing example.
4. Explain why bool('0') is True but bool(0) is False.
5. Correct a program with invalid identifiers and indentation.

Python Coding Master Book Page 9


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 2: Conditional statements


and loops
Control flow decides which statements run and how often they repeat. The key is to define a precise
condition and trace changes to loop variables.

2.1 if, elif and else


Grade classification

mark = int(input())

if mark < 0 or mark > 100:


print("invalid")
elif mark >= 90:
print("A")
elif mark >= 75:
print("B")
elif mark >= 60:
print("C")
else:
print("D")

Conditions are checked from top to bottom. Only the first true branch of an if/elif/else chain runs. Put
more specific or higher threshold conditions before broader ones.

2.2 Nested conditions and conditional expressions


Nested condition and ternary expression

age = 22
has_id = True

if age >= 18:


if has_id:
print("entry allowed")
else:
print("ID required")
else:
print("under age")

status = "pass" if 72 >= 40 else "fail"


print(status)

A conditional expression is suitable for one simple value choice. Use a normal if block when there
are several actions or complex branches.

Python Coding Master Book Page 10


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

2.3 for loops and range


A for loop visits items from an iterable. range(start, stop, step) produces integers with stop
excluded. A negative step is required for a decreasing range.

range and accumulation

total = 0
for number in range(1, 6):
total += number
print(total) # 15

for number in range(10, 0, -2):


print(number, end=" ")

Expression Values Reason

range(5) 0, 1, 2, 3, 4 Start defaults to 0; stop excluded.

range(2, 6) 2, 3, 4, 5 Step defaults to 1.

range(1, 8, 2) 1, 3, 5, 7 Increase by 2.

range(5, 0, -1) 5, 4, 3, 2, 1 Negative step decreases.

range(5, 0) Empty Positive default step cannot reach 0.

2.4 while loops


A while loop repeats while its condition is true. Initialise state before the loop, update it inside and
prove that the condition eventually becomes false.

Digit sum

number = abs(int(input()))
digit_sum = 0

while number > 0:


digit_sum += number % 10
number //= 10

print(digit_sum)

Infinite-loop warning
If the loop variable is never updated, the condition may stay true forever. Trace the initial value, condition
and update before running.

Python Coding Master Book Page 11


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

2.5 break, continue, pass and loop else


Statement Effect

break Immediately exits the nearest loop.

continue Skips the rest of the current iteration.

pass Does nothing; useful as a temporary syntactic placeholder.

loop else Runs only when the loop finishes without break.

Prime test with loop else

number = int(input())

if number < 2:
print("not prime")
else:
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
print("not prime")
break
else:
print("prime")

2.6 enumerate and zip


enumerate supplies an index with each item. zip pairs items from several iterables and stops at the
shortest input.

Index and paired iteration

names = ["Asha", "Ravi", "Meera"]


marks = [81, 92, 76]

for position, name in enumerate(names, start=1):


print(position, name)

for name, mark in zip(names, marks):


print(f"{name}: {mark}")

2.7 Nested loops


Nested loops are useful for matrices, pair comparisons and patterns, but two loops over n items can
cost O(n^2). Before nesting, check whether a dictionary or set can avoid repeated searching.

Matrix traversal

matrix = [
[1, 2, 3],
[4, 5, 6]
]

for row in matrix:


for value in row:
print(value, end=" ")
print()

Chapter 2 practice
1. Print the multiplication table of a supplied number.
2. Count digits, vowels and spaces using loops.
3. Find whether a number is prime using loop else.
4. Print all pairs whose sum equals a target, then improve it using a set.
5. Traverse a matrix and calculate each row sum.

Python Coding Master Book Page 12


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 3: Strings
Strings are immutable sequences. Most assessment questions depend on indexing, slicing,
normalisation, counting and carefully defined case or whitespace rules.

3.1 Creating, indexing and slicing strings


Indexing and slicing

text = "PYTHON"

print(text[0]) # P
print(text[-1]) # N
print(text[1:4]) # YTH
print(text[:3]) # PYT
print(text[::2]) # PTO
print(text[::-1]) # NOHTYP

The stop index is excluded. A missing start or stop uses the sequence boundary. A negative step
reverses direction. Indexing outside the valid range raises IndexError, while a slice safely clips to
available boundaries.

3.2 Immutability, comparison and concatenation


A string cannot be changed at one index. Build a new string using slicing, replace or a list of
characters. String comparison is lexicographic and case-sensitive according to Unicode code points.

Creating changed strings

text = "cat"
# text[0] = "b" # TypeError

changed = "b" + text[1:]


print(changed) # bat

print("Apple" < "apple")


print("py" * 3) # pypypy

Python Coding Master Book Page 13


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

3.3 Essential string methods


Method Purpose Example result

lower()/upper() Change case in a new string. 'Py'.lower() -> 'py'

strip() Remove leading/trailing whitespace. ' x '.strip() -> 'x'

split() Split into a list. 'a b'.split() -> ['a','b']

[Link](items) Join strings. '-'.join(['a','b']) -> 'a-b'

replace(old,new) Replace occurrences. 'aba'.replace('a','x') -> 'xbx'

find(part) Return index or -1. 'cat'.find('z') -> -1

index(part) Return index or raise ValueError. 'cat'.index('a') -> 1

count(part) Count non-overlapping occurrences. 'banana'.count('a') -> 3

startswith()/endswith() Check prefix or suffix. '[Link]'.endswith('.py')

isdigit() All characters are digits and non-empty. '123'.isdigit() -> True

isalpha() All characters alphabetic and non-empty. 'abc'.isalpha() -> True

isalnum() All characters letters/digits and non-empty. 'a1'.isalnum() -> True

Normalising text

raw = " Python SQL "


clean = " ".join([Link]()).lower()
print(clean) # python sql

words = [Link]()
print("-".join(words))

3.4 Formatting and f-strings


Useful formatting

name = "Shiva"
score = 87.456

print(f"{name} scored {score:.2f}")


print(f"{'Topic':<12}{'Mark':>6}")
print(f"{'Python':<12}{88:>6}")
print("Binary:", f"{10:b}")

Format specifiers control alignment, width, precision and numeric representation. For assessment
output, follow spaces, decimal places and line breaks exactly.

Python Coding Master Book Page 14


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

3.5 Palindrome and anagram


Palindrome
Normalise according to the question. This version ignores case and non-alphanumeric characters.

Python 3 example

def is_palindrome(text):
clean = "".join([Link]() for ch in text if [Link]())
return clean == clean[::-1]

print(is_palindrome("Never odd or even"))

Anagram
Two normalised strings are anagrams when their character frequencies match.

Python 3 example

from collections import Counter

def is_anagram(first, second):


a = "".join([Link]() for ch in first if [Link]())
b = "".join([Link]() for ch in second if [Link]())
return Counter(a) == Counter(b)

print(is_anagram("Listen", "Silent"))

Sorting characters also works in O(n log n). Counter-based comparison is average O(n) and
communicates the frequency requirement directly.

3.6 Character frequency and first non-repeating character


Two-pass frequency pattern

def first_unique(text):
counts = {}
for char in text:
counts[char] = [Link](char, 0) + 1

for char in text:


if counts[char] == 1:
return char
return None

print(first_unique("swiss")) # w

Python Coding Master Book Page 15


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

3.7 Reversing words and longest unique substring


Reverse word order

sentence = "Python makes coding clear"


reversed_words = " ".join([Link]()[::-1])
print(reversed_words)

Longest substring without repeated characters


Maintain a window [left, right]. When a repeated character lies inside the window, move left past its previous
position.

Python 3 example

def longest_unique_length(text):
last_seen = {}
left = 0
best = 0

for right, char in enumerate(text):


if char in last_seen and last_seen[char] >= left:
left = last_seen[char] + 1
last_seen[char] = right
best = max(best, right - left + 1)

return best

print(longest_unique_length("abcabcbb")) # 3

String practice
1. Count vowels, consonants, digits and spaces.
2. Remove duplicate characters while preserving order.
3. Find the most frequent character with deterministic tie handling.
4. Compress aaabbc as a3b2c1.
5. Find the longest common prefix of several words.
6. Check whether one string is a rotation of another.

Python Coding Master Book Page 16


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 4: Lists, tuples, sets and


dictionaries
Choose a data structure from the required operations: order, duplicates, lookup speed, mutability
and key-value relationships.

4.1 Lists: creation, access and methods


Core list operations

values = [4, 2, 7]
[Link](9)
[Link]([1, 5])
[Link](1, 8)

[Link](7)
last = [Link]()
print(values, last)

Method Effect Return value

append(x) Add one item at end. None

extend(items) Add every item from iterable. None

insert(i,x) Insert before index i. None

remove(x) Remove first equal value. None or ValueError

pop(i) Remove and return item; default last. Removed item

clear() Remove all items. None

sort() Sort the same list. None

reverse() Reverse the same list. None

Method return trap


Methods such as append, extend, insert, sort and reverse modify the list and return None. Do not write values
= [Link](). Use sorted(values) when a new sorted list is required.

Python Coding Master Book Page 17


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

4.2 List slicing, sorting and comprehension


Slicing and custom sorting

numbers = [5, 1, 8, 3, 8]
copy_part = numbers[1:4]
reversed_copy = numbers[::-1]

words = ["pear", "fig", "banana"]


by_length = sorted(words, key=len)
by_length_desc = sorted(words, key=len, reverse=True)

print(copy_part, reversed_copy)
print(by_length, by_length_desc)

List comprehensions

squares = [n * n for n in range(1, 6)]


evens = [n for n in range(10) if n % 2 == 0]
matrix = [[row * 3 + col for col in range(3)] for row in range(2)]
flat = [value for row in matrix for value in row]

print(squares)
print(evens)
print(matrix)
print(flat)

A comprehension should remain readable. Use a normal loop when transformation, validation and
error handling are complex.

4.3 Nested lists and matrices


Transpose a matrix

matrix = [
[1, 2, 3],
[4, 5, 6]
]

transpose = [
[matrix[row][col] for row in range(len(matrix))]
for col in range(len(matrix[0]))
]

print(transpose) # [[1, 4], [2, 5], [3, 6]]

Python Coding Master Book Page 18


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

4.4 Tuples
A tuple is an ordered immutable sequence. It is useful for fixed records, returning several values and
dictionary keys when all its elements are hashable.

Packing, unpacking and methods

record = ("Asha", 82, "CSE")


name, mark, branch = record

single = (5,) # comma makes a one-item tuple


print([Link](82))
print([Link]("CSE"))

point_to_value = {(2, 3): "occupied"}


print(point_to_value[(2, 3)])

List Tuple

Mutable Immutable

Uses square brackets Usually uses parentheses

Cannot be a dictionary key Can be a key if elements are hashable

More methods for modification Only count and index methods

4.5 Sets
A set stores unique hashable values and supports average O(1) membership. Normal sets are
mutable and unhashable; frozenset is immutable and hashable.

Set operations

first = {1, 2, 3, 4}
second = {3, 4, 5}

print(first | second) # union


print(first & second) # intersection
print(first - second) # difference
print(first ^ second) # symmetric difference
print({1, 2} <= first) # subset

Use add to insert one item, update to insert many, remove when absence should raise KeyError and
discard when absence should be ignored.

Python Coding Master Book Page 19


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

4.6 Dictionaries
A dictionary maps unique hashable keys to values and preserves insertion order. Lookup, insertion
and deletion are average O(1).

Dictionary operations

student = {"name": "Ravi", "mark": 78}


student["branch"] = "CSE"
student["mark"] = 82

print([Link]("phone", "not supplied"))

for key, value in [Link]():


print(key, value)

squares = {n: n * n for n in range(1, 5)}


print(squares)

Method/view Purpose

get(key, default) Read without KeyError when missing.

keys() Dynamic view of keys.

values() Dynamic view of values.

items() Dynamic view of key-value pairs.

update(mapping) Merge or overwrite supplied keys.

pop(key) Remove key and return its value.

setdefault(key, default) Get existing value or insert default.

4.7 Frequency maps, nested dictionaries and merging


Frequency and grouped records

words = ["sql", "python", "sql", "cloud"]


frequency = {}
for word in words:
frequency[word] = [Link](word, 0) + 1

students = {
101: {"name": "Asha", "mark": 88},
102: {"name": "Ravi", "mark": 74},
}

left = {"a": 1, "b": 2}


right = {"b": 5, "c": 3}
merged = left | right
print(frequency, students[101]["mark"], merged)

Python Coding Master Book Page 20


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

4.8 Stack, queue, Counter, defaultdict and heap


Structure Main operations Use

Stack/list append, pop Last-in, first-out processing

Queue/deque append, popleft First-in, first-out processing

Counter Count hashable items Frequency, most_common

defaultdict Creates a default value Grouping and accumulation

heapq heappush, heappop Priority queue and top-k

Additional structures

from collections import Counter, defaultdict, deque


import heapq

queue = deque(["A", "B"])


[Link]("C")
print([Link]())

counts = Counter("banana")
print(counts.most_common(2))

groups = defaultdict(list)
for name in ["Asha", "Anil", "Ravi"]:
groups[name[0]].append(name)

heap = []
for value in [7, 2, 9, 1]:
[Link](heap, value)
print([Link](heap))

4.9 Collection complexity


Operation List Set/dict Deque Heap

Append at end O(1) amortised O(1) average insert O(1) O(log n) push

Membership O(n) O(1) average O(n) O(n)

Remove first/left O(n) O(1) average by key O(1) O(log n) min

Sort O(n log n) Convert then sort Convert then Repeated pops O(n
sort log n)

Data-structure practice
1. Remove duplicates from a list while preserving order.
2. Merge dictionaries and add values for duplicate keys.
3. Validate balanced brackets using a stack.
4. Simulate a ticket queue using deque.
5. Return the three largest values using heapq.
6. Group words by their first letter with defaultdict.
7. Find common and unique subjects using set operations.

Python Coding Master Book Page 21


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 5: Functions and scope


Functions divide a problem into named, testable operations. Understand argument binding, return
values, scope and the difference between mutation and rebinding.

5.1 Defining, calling and returning


Function basics

def calculate_total(price, quantity):


total = price * quantity
return total

result = calculate_total(25.5, 4)
print(result)

def minimum_and_maximum(values):
return min(values), max(values)

smallest, largest = minimum_and_maximum([5, 2, 8])

A function without an explicit return returns None. return ends the current function call immediately.
A function can return several values; Python packs them into a tuple.

5.2 Positional, keyword and default arguments


Argument forms

def describe(name, branch="CSE", active=True):


return f"{name} | {branch} | {active}"

print(describe("Asha"))
print(describe("Ravi", "ECE"))
print(describe(name="Meera", active=False))

Positional arguments bind by position. Keyword arguments bind by name. Positional arguments
must normally appear before keyword arguments in a call. Defaults should follow required
parameters.

Python Coding Master Book Page 22


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

5.3 *args and **kwargs


Variable-length arguments

def total(*numbers):
return sum(numbers)

def profile(name, **details):


return name, details

print(total(1, 2, 3, 4))
print(profile("Asha", branch="CSE", year=4))

values = [2, 5, 7]
print(total(*values))

options = {"branch": "IT", "year": 3}


print(profile("Ravi", **options))

* collects or expands positional values. ** collects or expands keyword values. The usual parameter
order is positional, *args, keyword-only parameters and **kwargs.

5.4 LEGB scope, global and nonlocal


Scope Meaning

Local Names created in the current function.

Enclosing Names in surrounding function scopes.

Global Names at module level.

Built-in Names such as len, print and sum.

Scope behaviour

count = 10

def outer():
message = "start"

def inner():
nonlocal message
message = "changed"
return message

inner()
return message

def change_global():
global count
count += 1

print(outer())
change_global()
print(count)

Shadowing warning
Do not name variables list, str, sum, max or input. The local name hides the built-in function and can cause
TypeError later.

Python Coding Master Book Page 23


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

5.5 Lambda and higher-order functions


A lambda is a small anonymous expression. Use it for a short key or callback. A higher-order
function receives or returns another function.

lambda, map, filter and reduce

from functools import reduce

students = [("Asha", 82), ("Ravi", 91), ("Meera", 76)]


ranked = sorted(students, key=lambda item: item[1], reverse=True)

numbers = [1, 2, 3, 4]
squares = list(map(lambda n: n * n, numbers))
evens = list(filter(lambda n: n % 2 == 0, numbers))
product = reduce(lambda a, b: a * b, numbers, 1)

print(ranked)
print(squares, evens, product)

Comprehensions are often clearer than map or filter for simple Python transformations. reduce is
useful for cumulative combination but a normal loop may be easier to explain.

5.6 Recursion
A recursive function calls itself on a smaller problem. It needs a base case and progress toward that
base case. Python has a recursion limit, so iterative solutions are usually better for very deep input.

Factorial and recursive sum

def factorial(n):
if n < 0:
raise ValueError("negative factorial")
if n <= 1:
return 1
return n * factorial(n - 1)

def recursive_sum(values):
if not values:
return 0
return values[0] + recursive_sum(values[1:])

Python Coding Master Book Page 24


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

5.7 Mutable arguments and default-argument trap


Mutation through a parameter

def add_marker(values):
[Link]("done")

items = [1, 2]
add_marker(items)
print(items) # [1, 2, 'done']

Safe default

def add_item(item, items=None):


if items is None:
items = []
[Link](item)
return items

print(add_item("python"))
print(add_item("sql"))

A default argument is evaluated once when the function is defined. A list default would be shared
across calls. None is an immutable sentinel that allows a fresh list to be created inside.

5.8 Generators and decorators


Generator

def even_numbers(limit):
for value in range(limit):
if value % 2 == 0:
yield value

for value in even_numbers(8):


print(value)

Simple decorator

from functools import wraps

def announce(function):
@wraps(function)
def wrapper(*args, **kwargs):
print("calling", function.__name__)
return function(*args, **kwargs)
return wrapper

@announce
def add(a, b):
return a + b

Functions practice
1. Write a function accepting any number of marks and returning average.
2. Write a function returning min, max and average as a tuple.
3. Demonstrate local, enclosing and global scope.
4. Implement factorial recursively and iteratively.
5. Correct a function with a shared mutable default.
6. Sort records with a lambda key.

Python Coding Master Book Page 25


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 6: Object-oriented
programming
OOP groups state and behaviour. For assessment questions, identify whether data belongs to an
instance or class, how methods are bound and which implementation inheritance selects.

6.1 Classes, objects, self and __init__


Class and object

class Student:
institute = "IARE"

def __init__(self, name, marks):


[Link] = name
[Link] = list(marks)

def average(self):
return sum([Link]) / len([Link])

student = Student("Asha", [80, 90, 85])


print([Link])
print([Link]())

self refers to the current instance. __init__ initialises a newly created instance. It does not create the
object itself and should normally return None.

6.2 Instance and class variables


Instance variable Class variable

Stored per object, usually through self. Stored on the class and shared by lookup.

Different instances can hold different values. One common default or configuration.

Example: [Link] Example: [Link]

Changing one instance does not change another. Assignment on an instance can shadow the class value.

Class variable behaviour

class Counter:
created = 0

def __init__(self):
[Link] += 1

first = Counter()
second = Counter()
print([Link]) # 2

Python Coding Master Book Page 26


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

6.3 Instance, class and static methods


Three method types

class Temperature:
scale = "C"

def __init__(self, value):


[Link] = value

def display(self):
return f"{[Link]}{[Link]}"

@classmethod
def from_fahrenheit(cls, value):
return cls((value - 32) * 5 / 9)

@staticmethod
def is_valid(value):
return value >= -273.15

temp = Temperature.from_fahrenheit(68)
print([Link]())
print(Temperature.is_valid(-10))

Method First parameter Main use

Instance method self Read or change one object's state.

Class method cls Alternative constructor or class-level behaviour.

Static method None automatically Related utility that needs no instance/class state.

6.4 Encapsulation and properties


Python encapsulation is based mainly on conventions. A leading underscore signals internal use. A
double leading underscore triggers name mangling. A property provides controlled attribute access
without changing caller syntax.

Validated property

class BankAccount:
def __init__(self, balance=0):
self._balance = 0
[Link] = balance

@property
def balance(self):
return self._balance

@[Link]
def balance(self, value):
if value < 0:
raise ValueError("balance cannot be negative")
self._balance = value

Python Coding Master Book Page 27


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

6.5 Inheritance and super


Single and multilevel inheritance

class Person:
def __init__(self, name):
[Link] = name

def describe(self):
return [Link]

class Employee(Person):
def __init__(self, name, employee_id):
super().__init__(name)
self.employee_id = employee_id

def describe(self):
return f"{[Link]} ({self.employee_id})"

class Developer(Employee):
def code(self):
return "coding"

dev = Developer("Asha", 101)


print([Link]())

Single inheritance has one direct parent. Multilevel inheritance forms a chain. Multiple inheritance
has more than one parent. Python uses method resolution order (MRO) to choose methods; super
follows this order.

Multiple inheritance and MRO

class A:
def show(self):
return "A"

class B(A):
pass

class C(A):
def show(self):
return "C"

class D(B, C):


pass

print(D().show())
print([cls.__name__ for cls in [Link]()])

6.6 Overriding and polymorphism


Overriding gives a subclass its own version of an inherited method. Polymorphism means code can
call the same interface on objects of different classes. Python does not provide signature-based
method overloading like Java; later definitions replace earlier ones.

Python Coding Master Book Page 28


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Polymorphic method call

class Shape:
def area(self):
raise NotImplementedError

class Rectangle(Shape):
def __init__(self, width, height):
[Link], [Link] = width, height

def area(self):
return [Link] * [Link]

class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return 3.14159 * [Link] ** 2

for shape in [Rectangle(3, 4), Circle(2)]:


print([Link]())

Python Coding Master Book Page 29


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

6.7 Abstraction and abstract classes


Abstract base class

from abc import ABC, abstractmethod

class Payment(ABC):
@abstractmethod
def pay(self, amount):
pass

class CardPayment(Payment):
def pay(self, amount):
return f"paid {amount} by card"

payment = CardPayment()
print([Link](500))

An abstract class cannot be instantiated while required abstract methods remain unimplemented. It
defines an interface contract for subclasses.

6.8 Composition
Composition models a has-a relationship. It is often clearer than inheritance when one object uses
another service rather than being a specialised form of it.

Composition

class Engine:
def start(self):
return "engine started"

class Car:
def __init__(self, engine):
[Link] = engine

def start(self):
return [Link]()

car = Car(Engine())
print([Link]())

Python Coding Master Book Page 30


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

6.9 Magic methods


Method Triggered by Purpose

__str__ str(obj), print(obj) Readable user-facing representation

__repr__ repr(obj), interactive display Developer-facing representation

__len__ len(obj) Logical length

__eq__ obj1 == obj2 Value equality

__lt__ obj1 < obj2 Ordering comparison

__iter__ for item in obj Iteration protocol

__contains__ item in obj Membership test

Magic methods

class Course:
def __init__(self, name, students):
[Link] = name
[Link] = list(students)

def __str__(self):
return [Link]

def __repr__(self):
return f"Course({[Link]!r}, {[Link]!r})"

def __len__(self):
return len([Link])

def __eq__(self, other):


return isinstance(other, Course) and [Link] == [Link]

6.10 Mini OOP program


Library item model

from abc import ABC, abstractmethod

class LibraryItem(ABC):
def __init__(self, title):
[Link] = title
[Link] = True

@abstractmethod
def loan_days(self):
pass

def borrow(self):
if not [Link]:
raise ValueError("not available")
[Link] = False

class Book(LibraryItem):
def loan_days(self):
return 14

class Magazine(LibraryItem):
def loan_days(self):
return 7

items = [Book("Python"), Magazine("Cloud Monthly")]


for item in items:
print([Link], item.loan_days())

Python Coding Master Book Page 31


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

OOP practice
1. Create Employee and Manager classes with overridden bonus calculation.
2. Create an abstract Shape hierarchy with area and perimeter.
3. Create a BankAccount with validated deposit and withdrawal.
4. Demonstrate instance, class and static methods in one class.
5. Create a composition example using Order and PaymentService.
6. Add __str__, __repr__, __len__ and __eq__ to a custom collection.

Python Coding Master Book Page 32


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 7: File handling


Use context managers, explicit encodings and narrow exception handling. Decide whether a task
needs full-file reading or streaming line by line.

7.1 Opening files and modes


Mode Meaning If file exists If missing

r Read text Read from start FileNotFoundError

w Write text Truncates existing content Creates file

a Append text Writes at end Creates file

x Exclusive create FileExistsError Creates file

b Binary modifier Bytes, e.g. rb/wb Depends on base mode

+ Read/write modifier Allows both operations Depends on base mode

Safe text writing and reading

with open("[Link]", "w", encoding="utf-8") as file:


[Link]("Python\n")
[Link]("SQL\n")

with open("[Link]", "r", encoding="utf-8") as file:


content = [Link]()

print(content)

with closes the file even if an exception occurs. Avoid depending on automatic closing by the
garbage collector.

Python Coding Master Book Page 33


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

7.2 read, readline, readlines, write and writelines


Different reading styles

with open("[Link]", encoding="utf-8") as file:


first_chunk = [Link](6)
next_line = [Link]()

with open("[Link]", encoding="utf-8") as file:


all_lines = [Link]()

with open("[Link]", "w", encoding="utf-8") as file:


[Link](["one\n", "two\n"])

read() returns one string. readline() returns one line including its newline when present. readlines()
returns a list of lines. Iterating directly over the file streams lines and is best for large files.

7.3 Counting lines, words and characters


Streaming file statistics

def file_statistics(path):
lines = words = characters = 0

with open(path, encoding="utf-8") as file:


for line in file:
lines += 1
words += len([Link]())
characters += len(line)

return lines, words, characters

Python Coding Master Book Page 34


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

7.4 CSV and JSON files


CSV with dictionaries

import csv

with open("[Link]", "w", newline="", encoding="utf-8") as file:


writer = [Link](file, fieldnames=["name", "mark"])
[Link]()
[Link]({"name": "Asha", "mark": 88})

with open("[Link]", newline="", encoding="utf-8") as file:


for row in [Link](file):
print(row["name"], int(row["mark"]))

JSON

import json

data = {"name": "Asha", "skills": ["Python", "SQL"]}

with open("[Link]", "w", encoding="utf-8") as file:


[Link](data, file, indent=2)

with open("[Link]", encoding="utf-8") as file:


loaded = [Link](file)

print(loaded["skills"])

CSV values are read as strings unless converted. JSON supports objects, arrays, strings, numbers,
booleans and null; Python maps them to dict, list, str, numeric types, bool and None.

7.5 Paths and missing files


pathlib and error handling

from pathlib import Path

path = Path("data") / "[Link]"

try:
text = path.read_text(encoding="utf-8")
except FileNotFoundError:
print(f"missing file: {path}")
else:
print(text)

File-handling practice
1. Count line, word and character totals.
2. Copy only lines containing ERROR into another file.
3. Read CSV marks and calculate the average.
4. Update a JSON record and save it safely.
5. List all .txt files in a directory using pathlib.

Python Coding Master Book Page 35


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 8: Modules, packages and


important libraries
A module organises reusable names in one Python file. A package groups modules. Imports create
namespaces and execute top-level module code once per process.

8.1 Import forms and aliases


Import styles

import math
from statistics import mean
from datetime import date as Date

print([Link](81))
print(mean([70, 80, 90]))
print([Link]())

Prefer explicit imports. Avoid from module import * because it hides the source of names and can
overwrite existing names.

8.2 Custom modules, packages and main guard


[Link]

def add(a, b):


return a + b

def subtract(a, b):


return a - b

if __name__ == "__main__":
print(add(2, 3))

When [Link] runs directly, __name__ equals '__main__'. When imported, __name__ equals the
module name, so demonstration code under the guard does not run. A package normally contains
__init__.py and one or more module files.

Python Coding Master Book Page 36


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

8.3 math, random, datetime and statistics


Library High-value names Use

math sqrt, ceil, floor, factorial, gcd, pi Numeric operations

random randint, choice, shuffle, sample Pseudo-random selection

datetime date, datetime, timedelta Dates, times and differences

statistics mean, median, mode, stdev Descriptive statistics

Standard-library examples

import math
import random
from datetime import date, timedelta
from statistics import mean, median

print([Link](48, 18))
print([Link](["Python", "SQL", "Cloud"]))

today = [Link]()
print(today + timedelta(days=7))

marks = [70, 85, 90, 75]


print(mean(marks), median(marks))

Randomness note
random is suitable for simulation and games, not passwords or security tokens. Use the secrets module for
security-sensitive random values.

Python Coding Master Book Page 37


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

8.4 collections, itertools and functools


Library Important tools

collections Counter, defaultdict, deque, namedtuple

itertools chain, combinations, permutations, product, islice

functools reduce, wraps, lru_cache, partial

Combinations and caching

from functools import lru_cache


from itertools import combinations

print(list(combinations([1, 2, 3], 2)))

@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(30))

itertools tools are lazy iterators. combinations does not repeat order; permutations considers order;
product forms Cartesian combinations.

8.5 json, csv, os and pathlib


Library Typical use

json Serialise and parse structured JSON data.

csv Read and write comma-separated rows.

os Environment, process and legacy path operations.

pathlib Object-oriented paths, traversal and file helpers.

Path inspection

import os
from pathlib import Path

print([Link]())

folder = Path(".")
python_files = [[Link] for path in [Link]("*.py")]
print(python_files)

Modules and libraries practice


1. Create and import a custom calculator module.
2. Use datetime to find the date 30 days from today.
3. Use Counter to print the three commonest words.
4. Use [Link] to generate all pairs.
5. Use pathlib to find files by extension.

Python Coding Master Book Page 38


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 9: Exception handling


Exceptions separate normal results from failure paths. Catch only errors you can handle, preserve
useful information and use finally for cleanup that must occur.

9.1 Syntax errors and runtime exceptions


Category When found Example

SyntaxError Before execution of invalid source. Missing colon or unmatched parenthesis

IndentationError While parsing block structure. Unexpected or inconsistent indentation

Runtime exception While executing valid syntax. Division by zero or missing key

Logical error Program runs but result is wrong. Incorrect condition or formula

9.2 try, except, else and finally


Complete exception flow

try:
numerator = int(input())
denominator = int(input())
result = numerator / denominator
except ValueError:
print("enter integers")
except ZeroDivisionError:
print("denominator cannot be zero")
else:
print(result)
finally:
print("calculation finished")

else runs only when the try block succeeds. finally normally runs whether success, handled failure,
return or propagation occurs. Put only statements that may raise the intended exception inside try.

Python Coding Master Book Page 39


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

9.3 raise and custom exceptions


Validation with a custom exception

class InvalidMarkError(ValueError):
pass

def validate_mark(mark):
if not 0 <= mark <= 100:
raise InvalidMarkError("mark must be between 0 and 100")
return mark

try:
validate_mark(120)
except InvalidMarkError as error:
print(error)

Exception Typical cause

ValueError Correct type, unsuitable value

TypeError Unsupported operation or argument type

IndexError Sequence index outside range

KeyError Missing dictionary key

ZeroDivisionError Division or modulo by zero

FileNotFoundError Requested file path is absent

9.4 Exception best practices



Catch the narrowest expected exception.

Avoid bare except because it hides programming errors and interrupts.

Do not use exceptions as ordinary loop conditions when a direct test is clear.

Add context when re-raising an error.

Use with for files and resources.

Return a result or raise an exception consistently; do not silently mix error strings with valid
values.

Adding context

def load_number(path):
try:
with open(path, encoding="utf-8") as file:
return int([Link]().strip())
except FileNotFoundError:
raise
except ValueError as error:
raise ValueError(f"invalid number in {path}") from error

Exception practice
1. Safely read two integers and divide them.
2. Raise a custom InsufficientBalanceError.
3. Handle a missing JSON file and invalid JSON separately.
4. Explain the execution order of try, except, else and finally.

Python Coding Master Book Page 40


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 10: Important coding


patterns
These patterns convert common problem statements into reliable algorithms. Always state the
input, desired output, invariant, complexity and edge cases.

10.1 Time and space complexity


Complexity Meaning Example

O(1) Work does not grow with n. Dictionary lookup average

O(log n) Problem size repeatedly halves. Binary search

O(n) One pass over n items. Frequency count

O(n log n) Efficient comparison sorting. sorted(values)

O(n^2) All pairs or nested full scans. Simple duplicate pair check

O(2^n) Two choices per element. Naive subset recursion

Space complexity measures extra memory. A dictionary solution may use O(n) space to reduce
O(n^2) time to O(n). In an assessment, this is often a good trade-off.

10.2 Frequency counting and duplicate removal


Frequency map

def frequencies(values):
result = {}
for value in values:
result[value] = [Link](value, 0) + 1
return result

Remove duplicates while preserving order

def unique_in_order(values):
seen = set()
result = []
for value in values:
if value not in seen:
[Link](value)
[Link](value)
return result

Python Coding Master Book Page 41


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

10.3 Second largest and missing number


Second-largest distinct value

def second_largest(values):
first = second = None

for value in values:


if value == first or value == second:
continue
if first is None or value > first:
second, first = first, value
elif second is None or value > second:
second = value

return second

Missing number from 0 to n

def missing_number(values):
n = len(values)
expected = n * (n + 1) // 2
return expected - sum(values)

print(missing_number([3, 0, 1])) # 2

The sum formula assumes exactly one missing number, no duplicates and values from 0 through n.
State these assumptions. XOR can solve the same constraint without a potentially large sum in
fixed-width languages.

10.4 Two-sum and dictionary lookup


Return indices of a target pair

def two_sum(values, target):


seen = {}

for index, value in enumerate(values):


needed = target - value
if needed in seen:
return seen[needed], index
seen[value] = index

return None

At each index, the dictionary stores values already seen. The invariant is that any returned first
index is earlier than the current index. Time is O(n) average and extra space is O(n).

Python Coding Master Book Page 42


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

10.5 Two pointers


Two pointers are useful when input is sorted or when a range can be narrowed from both ends.

Pair sum in sorted input

def pair_sum_sorted(values, target):


left, right = 0, len(values) - 1

while left < right:


current = values[left] + values[right]
if current == target:
return values[left], values[right]
if current < target:
left += 1
else:
right -= 1

return None

Move zeroes while preserving order

def move_zeroes(values):
write = 0

for value in values:


if value != 0:
values[write] = value
write += 1

while write < len(values):


values[write] = 0
write += 1

10.6 Sliding window


Maximum sum of k consecutive values

def max_window_sum(values, k):


if k <= 0 or k > len(values):
raise ValueError("invalid window")

current = sum(values[:k])
best = current

for right in range(k, len(values)):


current += values[right] - values[right - k]
best = max(best, current)

return best

A fixed window adds the entering value and removes the leaving value. A variable window moves
the left boundary while a validity condition is broken.

Python Coding Master Book Page 43


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

10.7 Prefix sums


Range-sum queries

def build_prefix(values):
prefix = [0]
for value in values:
[Link](prefix[-1] + value)
return prefix

def range_sum(prefix, left, right):


return prefix[right + 1] - prefix[left]

values = [2, 4, 1, 7]
prefix = build_prefix(values)
print(range_sum(prefix, 1, 3)) # 12

prefix[i] stores the sum before index i. The sum from left through right is prefix[right + 1] -
prefix[left]. Build time and space are O(n); each query is O(1).

10.8 Sorting with key


Custom sorting

records = [
{"name": "Asha", "mark": 82},
{"name": "Ravi", "mark": 91},
{"name": "Meera", "mark": 82},
]

ranked = sorted(
records,
key=lambda item: (-item["mark"], item["name"])
)

print(ranked)

The key returns a tuple: negative mark gives descending numeric order; name gives ascending tie
order. Python sorting is stable, so equal keys preserve original order.

Python Coding Master Book Page 44


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

10.9 Stack and queue problems


Balanced brackets

def balanced(text):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []

for char in text:


if char in "([{":
[Link](char)
elif char in pairs:
if not stack or [Link]() != pairs[char]:
return False

return not stack

Breadth-first queue pattern

from collections import deque

def process_queue(items):
queue = deque(items)
result = []

while queue:
[Link]([Link]())

return result

10.10 Matrix traversal


Main and secondary diagonal sums

def diagonal_sums(matrix):
n = len(matrix)
if any(len(row) != n for row in matrix):
raise ValueError("square matrix required")

main = sum(matrix[i][i] for i in range(n))


secondary = sum(matrix[i][n - 1 - i] for i in range(n))
return main, secondary

Python Coding Master Book Page 45


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

10.11 Basic recursion and memoisation


Binary search recursively

def binary_search(values, target, left=0, right=None):


if right is None:
right = len(values) - 1
if left > right:
return -1

middle = (left + right) // 2


if values[middle] == target:
return middle
if values[middle] < target:
return binary_search(values, target, middle + 1, right)
return binary_search(values, target, left, middle - 1)

Memoised Fibonacci

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

10.12 Edge-case checklist


Edge case Question

Empty input Return empty result, None, -1 or raise?

One item Does index or second-largest logic still work?

Duplicates Are duplicates allowed, ignored or counted?

Negative values Does zero initialisation produce a wrong maximum?

Whitespace/case Should strings be normalised?

Large input Will nested loops, recursion or full-file reading fail?

Ties Which tied answer should be returned?

Invalid k/index Raise, clamp or return a sentinel?

Coding-pattern practice
1. Find the first repeated and first non-repeated value.
2. Return the second-smallest distinct value.
3. Find a target pair in sorted and unsorted input.
4. Find maximum sum of any k consecutive values.
5. Answer several range-sum queries using a prefix array.
6. Validate brackets and remove adjacent duplicate characters with a stack.
7. Rotate a square matrix by 90 degrees.
8. Implement binary search iteratively and recursively.

Python Coding Master Book Page 46


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 11: Practice workbook


Attempt these without reading a solution. Use the exact function name, write at least two tests and
record time and space complexity.

11.1 Foundation problems


No. Problem Main topic

P1 Read three numbers and print min, max and average. Input, conversion

P2 Classify a year as leap or not. Conditions

P3 Print factors of a number. Loops

P4 Check prime and print the next prime. Loop else

P5 Calculate digit count, sum and reverse. while loop

P6 Print a formatted multiplication table. for/range/f-strings

P7 Find GCD without using [Link]. Euclidean loop

P8 Generate the first n Fibonacci values. Iteration

11.2 String problems


No. Problem Main idea

S1 Normalised palindrome check. Slicing

S2 Anagram check. Counter/dict

S3 First unique character. Two-pass count

S4 Run-length encoding. State tracking

S5 Longest word with first tie. split and max

S6 Remove duplicates preserving order. set plus result

S7 Longest substring without repeats. Sliding window

S8 Longest common prefix. Character comparison

Python Coding Master Book Page 47


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

11.3 Collection and function problems


No. Problem Main idea

C1 Second-largest distinct number. Two trackers

C2 Merge dictionaries and add overlapping values. Key union

C3 Group words by length. defaultdict

C4 Return top k frequent elements. Counter/heap

C5 Transpose and diagonal sums. Nested lists

C6 Balanced bracket validator. Stack

C7 Queue simulation with cancellations. deque

C8 Function accepting marks through *args. Variable arguments

C9 Memoised recursive Fibonacci. Recursion/cache

C10 Sort records by mark then name. lambda key

11.4 OOP, file and exception problems


No. Problem Main idea

O1 Employee hierarchy with overridden bonus. Inheritance

O2 Shape abstraction with polymorphic area. ABC/overriding

O3 BankAccount with custom exception. Property/raise

O4 Course class with magic methods. Data model

F1 Text-file statistics. Streaming

F2 CSV marks summary. csv module

F3 JSON settings loader with defaults. json/exception

F4 Find duplicate lines in a file. dict/set

Python Coding Master Book Page 48


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 12: Python MCQ and output


practice
Answer before checking the key. For output questions, trace types, object identity, mutation, scope
and control flow.

1. What type does input() return?


A. int
B. str
C. Depends on typed text
D. bytes

2. What is 7 // 2?
A. 3
B. 3.5
C. 4
D. 1

3. Which value is falsy?


A. '0'
B. [0]
C. {}
D. (0,)

4. What does dictionary membership test?


A. Values
B. Keys
C. Items only
D. Indexes

5. Which expression checks absence correctly?


A. x = None
B. x is None
C. x equals None
D. None(x)

6. What is 'python'[1:4]?
A. pyt
B. yth
C. ytho
D. tho

7. Which list method returns the removed item?


A. remove
B. pop
C. clear
D. sort

8. What does [Link]() return?


A. Sorted list
B. Tuple
C. None
D. Iterator

9. Which collection stores unique values?


A. list
B. tuple
C. set
D. str

10. Which can be a dictionary key?


A. list
B. dict
C. set
D. tuple of ints

Python Coding Master Book Page 49


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

11. What does *args collect?


A. Keyword values
B. Positional values
C. Exceptions
D. Imports

12. What does **kwargs collect?


A. Keyword values
B. Only lists
C. Only numbers
D. Class methods

13. Which scope is searched after local?


A. Built-in
B. Global
C. Enclosing
D. Module import

14. Why is items=[] a risky default?


A. Lists cannot be defaults
B. One list is shared across calls
C. It is immutable
D. It causes syntax error

15. What ends the current function call?


A. yield only
B. continue
C. return
D. pass

16. What does yield create?


A. A generator function
B. A class
C. A module
D. A file

17. Which parameter identifies an instance method object?


A. cls
B. self
C. this required keyword
D. obj keyword

18. What does super() follow?


A. File order only
B. MRO
C. Alphabetical order
D. Random choice

19. Which method supports print(obj)?


A. __len__
B. __str__
C. __eq__
D. __iter__

20. Which decorator defines a class method?


A. @staticmethod
B. @property
C. @classmethod
D. @abstract

21. Which mode truncates an existing text file?


A. r
B. a
C. w
D. x

Python Coding Master Book Page 50


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

22. Which mode fails if the file already exists?


A. x
B. w
C. a
D. r+

23. What does with open help guarantee?


A. Encryption
B. Closure/cleanup
C. JSON format
D. Sorting

24. Which block runs only when try succeeds?


A. except
B. else
C. raise
D. catch

25. Which block normally runs in success and failure?


A. else
B. finally
C. except only
D. if

26. Which error results from values[100]?


A. KeyError
B. IndexError
C. ValueError
D. NameError

27. Average set membership complexity is usually:


A. O(1)
B. O(log n)
C. O(n)
D. O(n^2)

28. Sorting n items is usually:


A. O(1)
B. O(log n)
C. O(n log n)
D. O(2^n)

29. Which structure gives efficient popleft?


A. list
B. deque
C. tuple
D. str

30. Which tool counts hashable values?


A. Path
B. Counter
C. reduce
D. date

Python Coding Master Book Page 51


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

12.2 MCQ answer key


Q Answer Why

1 B input always returns str.

2 A Floor division of positive operands gives 3.

3 C An empty dictionary is falsy.

4 B in checks dictionary keys.

5 B Identity comparison is standard for None.

6 B Stop index 4 is excluded.

7 B pop removes and returns an item.

8 C sort mutates and returns None.

9 C A set stores unique hashable values.

10 D A tuple of hashable values is hashable.

11 B *args collects extra positional arguments.

12 A **kwargs collects keyword arguments.

13 C LEGB searches enclosing after local.

14 B The mutable default is created once.

15 C return ends the call.

16 A A function containing yield returns a generator.

17 B self refers to the instance by convention.

18 B super follows method resolution order.

19 B __str__ supplies a readable string.

20 C @classmethod binds the class as cls.

21 C w truncates before writing.

22 A x is exclusive creation.

23 B The context manager closes the file.

24 B else runs only without an exception.

25 B finally is the cleanup path.

26 B An invalid sequence index raises IndexError.

27 A Hash membership is average constant time.

28 C Efficient comparison sorts are O(n log n).

29 B deque supports O(1) popleft.

30 B Counter counts hashable objects.

Python Coding Master Book Page 52


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 13: Final timed coding mock


Use 90 minutes for this Python-only mock: 10 minutes to read, 65 minutes to code and 15 minutes
to test and review.

13.1 Coding questions


No. Question Expected focus

M1 Normalise text and return the first non-repeating character. String + frequency map

M2 Return the second-largest distinct value or None. Edge cases + tracking

M3 Return indices of a target pair. Dictionary lookup

M4 Find longest substring without repeated characters. Sliding window

M5 Validate nested brackets. Stack

M6 Read a CSV of names and marks and return top student. CSV + conversion + tie rule

M7 Create Shape, Rectangle and Circle with polymorphic area. OOP

M8 Load an integer safely and explain handled errors. Exceptions

13.2 Testing checklist


Question type Tests

String Empty, one character, repeated, mixed case and spaces

Numeric list Empty, one item, duplicates, negative values and ties

Dictionary lookup No solution, duplicate values and target using same value twice

Window All unique, all repeated and repeated at boundaries

Stack Empty, correctly nested, wrong order and unclosed

File Missing, empty, malformed row and tied maximum

OOP Valid objects, invalid dimensions and overridden method

Exception Valid input, wrong type, zero and missing file

Python Coding Master Book Page 53


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

13.3 Model solution patterns


M1 - first non-repeating character

def first_non_repeating(text):
clean = [Link]()
counts = {}
for char in clean:
counts[char] = [Link](char, 0) + 1
for char in clean:
if counts[char] == 1:
return char
return None

M3 - target pair indices

def target_pair(values, target):


seen = {}
for index, value in enumerate(values):
needed = target - value
if needed in seen:
return seen[needed], index
seen[value] = index
return None

M5 - bracket validation

def valid_brackets(text):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for char in text:
if char in "([{":
[Link](char)
elif char in pairs:
if not stack or [Link]() != pairs[char]:
return False
return not stack

Completion standard
You are ready when you can solve at least six of the eight mock questions, explain complexity, and pass
boundary tests without copying a solution.

Python Coding Master Book Page 54


Cognizant Skill Cluster 2 Python | SQL | Cloud | GenAI

Chapter 14: Last-minute revision


sheets
Use these compact pages on assessment morning. Review rules and traps, not new topics.

14.1 Syntax and collection cheat sheet


Need Preferred construct

Fast lookup/count dict or Counter

Unique membership set

Ordered dynamic values list

Fixed immutable record tuple

FIFO processing [Link]

Priority processing heapq

Lazy sequence generator/yield

Safe file handling with open(..., encoding='utf-8')

Missing dictionary key get or defaultdict

Sort by custom fields sorted(..., key=...)

14.2 High-frequency traps


Trap Correct rule

input treated as a number input returns str; convert explicitly.

is used for value equality Use == for values; is for identity/None.

list method assigned back sort/append/reverse return None.

dictionary in checks values Membership checks keys.

mutable default retained data Use None and create inside.

LEFT/RIGHT slice endpoint included The stop index is excluded.

file not closed Use a context manager.

bare except Catch the narrow expected exception.

recursive call has no progress Define a base case and smaller input.

negative-only maximum starts at 0 Initialise from data or None.

14.3 Final submission checklist


1 Read whether the platform expects a function or a complete input/output program.
2 Use the exact function name and return type.
3 Remove debug prints that are not part of the required output.
4 Check indentation and imports.
5 Test empty, one-item, duplicate, negative and large inputs where relevant.
6 Check whether ties, case and whitespace have specified rules.
7 Dry-run one example line by line.
8 Estimate complexity and compare output formatting exactly.

Python Coding Master Book Page 55

You might also like