0% found this document useful (0 votes)
3 views54 pages

Python Notes

The document provides comprehensive notes on Python fundamentals, covering installation, variables, data types, input functions, type conversion, operators, decision-making, loops, and data structures like lists, tuples, and dictionaries. It emphasizes key concepts such as the importance of indentation, the distinction between mutable and immutable types, and common programming mistakes to avoid. Each section includes examples and rules to help reinforce understanding of Python programming principles.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views54 pages

Python Notes

The document provides comprehensive notes on Python fundamentals, covering installation, variables, data types, input functions, type conversion, operators, decision-making, loops, and data structures like lists, tuples, and dictionaries. It emphasizes key concepts such as the importance of indentation, the distinction between mutable and immutable types, and common programming mistakes to avoid. Each section includes examples and rules to help reinforce understanding of Python programming principles.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Day 1 Notes – Fundamentals

1. Python Setup
• Python must be installed and added to PATH.
• Use VS Code with Python extension.
• Run files using: python [Link]
• Avoid spaces in file names (use underscore _ instead).

2. Variables and Data Types


• Variable stores a value in memory.
• Python is case-sensitive: age ≠ Age.
• Common data types:
- int → whole numbers (10, 25)
- float → decimal numbers (3.5, 10.0)
- str → text ('10', 'hello')
- bool → True / False

3. input() Function
• input() ALWAYS returns a string.
• Text inside input() is only a prompt, not the value.
• Example:
age = input('Enter age: ') → str
age = int(input('Enter age: ')) → int

4. Type Conversion
• Type conversion changes data type.
• int('19') → 19
• Conversion does NOT change variable unless reassigned.
• Example:
age = int(age) # permanent conversion

5. Operators
Arithmetic Operators:
• + Addition
• - Subtraction
• * Multiplication
• / Division (always returns float)
• // Floor division (always goes down)
• % Modulus (remainder)
• ** Power
6. Float vs Integer
• int → no decimal
• float → decimal values
• / gives float for precision
• // cuts decimal part, no rounding

7. Modulus Operator (%)


• % gives remainder after division.
• Examples:
9 % 2 = 1 (odd)
10 % 2 = 0 (even)

8. Operator Behavior with Strings


• '12' + '3' → '123' (concatenation)
• '12' * 2 → '1212' (repetition)
• '12' + 2 → ERROR
• '12' / 2 → ERROR

9. type() Function
• type() shows data type.
• Output format:
<class 'str'>
<class 'int'>

10. Key Rules to Remember


• Printing value does not show type.
• Math works only on numbers.
• Conversion must be explicit.
• Operators depend on data type.
• Python executes code top to bottom.
Python Day 2 Notes – Decision Making (if, elif, else)

1. What is Decision Making?


Decision making allows a program to choose different paths based on conditions.
In Python, this is done using if, elif, and else statements.

2. if Statement
Definition:
The if statement executes a block of code only if the condition is True.

Syntax:
if condition:
code block

Important points:
• Condition must evaluate to True or False
• Indentation is mandatory
• Code outside indentation always runs

3. Indentation (Very Important)


Indentation means spaces at the beginning of a line.
Python uses indentation to define code blocks instead of braces {}.

Rules:
• Same indentation = same block
• Less indentation = block ends
• Missing indentation after ':' causes IndentationError
• Standard indentation is 4 spaces

4. if – else Statement
Definition:
The else block runs only when the if condition is False.

Rules:
• Only one block runs (either if or else)
• else has no condition
• else must be aligned with if

5. if – elif – else Statement


Definition:
elif allows checking multiple conditions one by one.
Key rules:
• Conditions are checked top to bottom
• First True condition runs
• Remaining blocks are skipped
• Only ONE block executes

6. Order of Conditions (Critical)


Always place stricter conditions first and looser ones later.

Correct example:
if marks >= 90:
print('A')
elif marks >= 75:
print('B')
elif marks >= 50:
print('C')
else:
print('Fail')

Wrong order causes logical bugs (wrong output but no error).

7. Common Mistakes to Avoid


• Using '=' instead of '==' in conditions
• Wrong indentation
• Putting loose conditions before strict ones
• Using multiple if instead of if–elif–else
• Expecting multiple blocks to run in if–elif–else

8. Logical Bug vs Syntax Error


Syntax Error:
• Python cannot understand the code
• Program does not run

Logical Bug:
• Code runs but gives wrong output
• Usually caused by wrong condition order

9. Key Rules to Memorize


• Colon ':' starts a block
• Indentation defines logic
• if–elif–else selects only one path
• Order of conditions matters
• First True condition wins
Python Day 3 Notes – Logical Operators

1. What are Logical Operators?


Logical operators are used to combine or modify conditions that return True or False.
They are mainly used with if–elif–else statements.

2. Boolean Values
Boolean values represent truth values:
• True
• False

Boolean variables usually answer yes/no questions.


Example:
is_admin = True
logged_in = False

3. and Operator
Definition:
The 'and' operator returns True only if ALL conditions are True.

Truth table:
True and True → True
True and False → False
False and True → False
False and False → False

Example:
if age >= 18 and has_id == 'yes':
print('Allowed')

4. or Operator
Definition:
The 'or' operator returns True if AT LEAST ONE condition is True.

Truth table:
True or False → True
False or True → True
False or False → False

Important:
Use 'or' only when multiple independent conditions are acceptable.
5. not Operator (Very Important)
Definition:
The 'not' operator reverses the boolean value.

Examples:
not True → False
not False → True

Example in code:
logged_in = False
if not logged_in:
print('Please log in')

6. Understanding Variable Meaning


Boolean variable names already carry meaning.

Example:
is_admin = False
Meaning: User is NOT admin

not is_admin = True


Meaning: It is true that user is NOT admin

Important Rule:
'not' flips the value, NOT the meaning of the variable name.

7. Operator Precedence
Order of evaluation in logical expressions:
1. not
2. and
3. or

Example:
not is_admin and has_access
is evaluated as:
(not is_admin) and has_access

8. Input Normalization (Real-World Practice)


User input is unpredictable.
Always normalize string input.

Example:
has_id = input('Do you have ID? ').strip().lower()
This handles:
YES, Yes, yes, yEs

9. Common Mistakes to Avoid


• Using AND / OR instead of and / or
• Assuming 'not variable' changes variable meaning
• Using unnecessary logical operators
• Not normalizing user input
• Confusing multiple if with if–elif–else

10. Key Rules to Memorize


• Boolean variables represent yes/no states
• 'and' requires all conditions True
• 'or' requires at least one condition True
• 'not' flips True/False only
• Read conditions in plain English
• Clear variable naming prevents logic bugs
Python Day 4 Notes – Loops

1. What is a Loop?
A loop is used to execute a block of code repeatedly without writing it again and again.
Loops are useful when we want repetition based on a condition or a fixed range.

2. Types of Loops in Python


Python mainly provides two types of loops:
1. while loop
2. for loop

3. while Loop
Definition:
A while loop runs as long as the given condition is True.

Syntax:
while condition:
code block

Important points:
• Condition is checked before every iteration
• Loop stops when condition becomes False
• Loop variable must be updated manually

4. Infinite Loop (Common Mistake)


If the loop variable is not updated, the condition never becomes False.
This results in an infinite loop where the program never stops.

5. for Loop
Definition:
A for loop is used to iterate over a sequence like range, list, or string.

Syntax:
for variable in sequence:
code block

for loop automatically handles iteration and is safer than while loop.

6. range() Function
The range() function generates a sequence of numbers.

Forms:
range(stop)
range(start, stop)
range(start, stop, step)

Important rule:
• The stop value is never included.

7. break Statement
The break statement is used to exit a loop immediately.

Important points:
• break stops the loop instantly
• Code after break inside loop is not executed
• break is usually used with a condition

8. Loop Direction (Logic)


Before writing a loop, always decide:
• Start value
• End condition
• Direction (increment or decrement)

Condition and update must move towards loop termination.

9. Code Outside Loop


Any code written outside a loop executes only once after the loop finishes.
This is commonly used to print final messages.

10. Common Mistakes to Avoid


• Forgetting to update loop variable
• Wrong loop condition
• Using break without condition
• Expecting loop to stop automatically
• Confusing loop direction

11. Key Rules to Memorize


• while loop depends on condition
• for loop depends on range/sequence
• range() excludes stop value
• break exits loop immediately
• Logic is more important than syntax
Python Day 5 Notes – continue, Nested Loops & Patterns

1. continue Statement
The continue statement is used inside loops to skip the current iteration and move to the
next one.

Key points:
• continue does NOT stop the loop
• It skips only the current iteration
• Control goes back to the loop condition

Difference:
break → stops the loop completely
continue → skips one iteration only

2. Nested Loops
A nested loop is a loop inside another loop.

Execution rule:
• Outer loop runs once
• Inner loop runs fully for each outer loop iteration

Important:
The inner loop always finishes first.

3. Execution Order in Nested Loops


Example:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)

Flow:
i = 1 → j runs 1 to 3
i = 2 → j runs 1 to 3
i = 3 → j runs 1 to 3

4. Pattern Printing – Core Idea


Pattern printing trains loop logic.

Rules:
• Outer loop controls rows
• Inner loop controls columns (items in a row)
• Inner loop usually depends on outer loop variable

5. print() and end Parameter


By default, print() moves to a new line.

end=' ' prevents newline and prints on the same line.

Example:
print('*', end=' ')
print() # moves to next line

6. Pattern Example (Right Triangle)


Code:
for i in range(1, 5):
for j in range(1, i + 1):
print('*', end=' ')
print()

Output:
*
**
***
****

7. continue in Nested Loops


When continue is used inside an inner loop:
• Only that inner iteration is skipped
• No output is produced for that iteration
• No blank line is created

8. Common Mistakes
• Using break instead of continue
• Expecting continue to print blank lines
• Hard-coding patterns instead of using logic
• Forgetting that inner loop finishes first
• Wrong indentation of print()

9. Key Rules to Memorize


• continue skips one iteration
• break stops loop completely
• Inner loop always finishes first
• Outer loop controls rows
• Pattern logic > pattern output
• Indentation controls execution
Python Day 6 Notes – Lists & Strings

1. What is a List?
A list is a collection of multiple values stored in a single variable.
Lists are written using square brackets [].

Example:
numbers = [10, 20, 30, 40]

2. Printing a List
When we print a list, Python shows the complete structure using square brackets.
This is the official representation of a list.

print(numbers) → [10, 20, 30, 40]

3. List Indexing
Indexing means accessing elements using their position.

Important rules:
• Index starts from 0
• Last index can be accessed using -1

Example:
numbers[0] → first element
numbers[-1] → last element

4. List Mutability
Lists are mutable, which means their elements can be changed after creation.

Example:
numbers[1] = 99
This changes the second element of the list.

5. Looping Through a List


We can loop through list elements directly using a for loop.

Example:
for num in numbers:
print(num)

Here, num holds values, not indexes.


6. Leading Zero Error (Important)
In Python 3, integers cannot start with a leading zero.
Example:
04 → invalid
4 → valid

If you want to display a number like 04, use formatting or strings.

7. Strings as Sequences
Strings are sequences of characters.
They support indexing and looping just like lists.

Example:
name = 'Python'
name[0] → 'P'

8. String Immutability
Strings are immutable, which means their characters cannot be changed.

Example:
name[0] = 'J' → Error

To change a string, we must create a new string.

9. Modifying Strings Correctly


Strings are modified by creating new strings using slicing or methods.

Example:
name = 'Python'
name = name[:2] + 'k' + name[3:]
Result: 'Pykhon'

10. List vs String (Key Difference)


List → Mutable → Elements can be changed
String → Immutable → Characters cannot be changed

This difference is due to mutability, not because of size or number of elements.

11. Key Rules to Remember


• List uses [] and is mutable
• String uses '' or "" and is immutable
• Index starts from 0
• Negative indexing starts from -1
• Formatting controls display, not stored value
Python Day 7 Notes – List Methods

1. append()
append() is used to add a single element at the end of a list.

Example:
numbers = [10, 20, 30]
[Link](40)

Result:
[10, 20, 30, 40]

Important:
• append() modifies the list in place
• append() returns None

2. insert()
insert() is used to add an element at a specific index.

Syntax:
[Link](index, value)

Example:
numbers = [10, 20, 30]
[Link](1, 99)

Result:
[10, 99, 20, 30]

3. remove()
remove() deletes an element by value.

Key points:
• Removes only the first occurrence
• Does not return the removed value
• Error if value not found

Example:
numbers = [10, 20, 30, 20]
[Link](20)
Result:
[10, 30, 20]
4. pop()
pop() removes an element by index and returns it.

Key points:
• Default index is -1 (last element)
• Returns the removed value

Example:
numbers = [10, 20, 30]
x = [Link]()
Result:
Removed value: 30
Remaining list: [10, 20]

5. len()
len() is used to find the number of elements in a list.

Example:
numbers = [3, 6, 9, 12]
len(numbers) → 4

6. In-place Modification Rule


List methods like append(), insert(), and remove() modify the list directly.
They return None.

Wrong:
numbers = [Link](4)

Correct:
[Link](4)

7. remove() vs pop()
remove() → deletes by value, returns nothing
pop() → deletes by index, returns the deleted value

8. Common Mistakes
• Assigning result of append() to a variable
• Confusing value-based remove() with index-based pop()
• Expecting remove() to return a value
• Forgetting pop() returns the removed element

9. Key Rules to Remember


• append() adds to end
• insert() adds at index
• remove() deletes first matching value
• pop() deletes and returns value
• len() gives size of list
• In-place methods return None
Python Day 8 Notes – Tuples

1. What is a Tuple?
A tuple is a collection of values similar to a list, but it is immutable.
Once created, its elements cannot be changed.

Example:
numbers = (10, 20, 30)

2. Tuple Characteristics
• Uses parentheses ()
• Ordered collection
• Immutable (cannot change, add, or remove elements)
• Faster and safer than lists for fixed data

3. Indexing and Looping


Tuples support indexing and looping just like lists.

Example:
names = ('Amit', 'Ravi', 'Sita')
names[0] → 'Amit'
names[-1] → 'Sita'

for name in names:


print(name)

4. Tuple Immutability
Tuple elements cannot be modified.

Example:
nums = (10, 20, 30)
nums[1] = 99 → TypeError

5. When to Use Tuples


Use tuples when data should not change.

Examples:
• Days of the week
• Months of the year
• Coordinates (x, y)
• Fixed configuration values
6. List vs Tuple
List → Mutable → []
Tuple → Immutable → ()

Rule:
If data may change → use list
If data must not change → use tuple
Python Day 9 Notes – Dictionaries

1. What is a Dictionary?
A dictionary stores data in key-value pairs.
Each key represents meaning, and each value stores data.

Example:
student = {
'name': 'Amit',
'age': 21,
'marks': 85
}

2. Dictionary Characteristics
• Uses curly braces {}
• Stores data as key : value
• Accessed by keys, not index
• Mutable (values can be changed)

3. Accessing Values
Values are accessed using keys.

Example:
student['name'] → 'Amit'
student['marks'] → 85

Indexing like student[0] is not allowed.

4. Adding and Updating Data


Same syntax is used to add or update data.

student['age'] = 22 # update
student['city'] = 'Mumbai' # add

5. Looping Through Dictionary


Looping through a dictionary gives keys one by one.

for key in student:


print(key, ':', student[key])
6. Why Dictionaries Are Powerful
Dictionaries store data meaningfully.
They are better than lists when data has labels.

Example:
List: ['Amit', 21, 85] # unclear
Dictionary: {'name':'Amit','age':21,'marks':85} # clear

7. When to Use Dictionaries


Use dictionaries when:
• Data has meaning
• You need labeled access
• Working with profiles, configs, JSON, APIs
Python Day 10 Notes – Sets & Brackets Guide

1. What is a Set?
A set is a collection of unique values.
It automatically removes duplicate elements and does not maintain order.

Example:
numbers = {1, 2, 3, 2, 1}
Result: {1, 2, 3}

2. Key Properties of Sets


• Stores only unique values
• Unordered collection
• Mutable (can add/remove elements)
• Does NOT support indexing
• Very fast for membership checking

3. Creating and Using Sets


Creating a set:
values = {'apple', 'banana', 'mango'}

Adding an element:
[Link]('orange')

Removing an element:
[Link]('banana')

4. Membership Testing with Sets


Sets are best used when checking whether a value exists.

Example:
if 'apple' in values:
print('Present')

This is much faster than checking in a list.

5. Real-life Use Cases of Sets


• Unique employee IDs
• Unique email addresses
• Enrollment numbers
• Removing duplicates from data
6. Brackets in Python – Complete Guide
Python uses different brackets for different purposes.
Understanding this avoids confusion.

Square Brackets [ ]
Used for:
• Lists → numbers = [1, 2, 3]
• Indexing → numbers[0]
• Slicing → numbers[1:3]

Purpose:
• Ordered data
• Mutable collections

Parentheses ( )
Used for:
• Tuples → data = (1, 2, 3)
• Function calls → print('Hello')
• Grouping expressions → (a + b) * c

Purpose:
• Fixed data
• Executing functions

Curly Braces { }
Used for:
• Dictionaries → {'name': 'Amit', 'age': 21}
• Sets → {'apple', 'banana'}

Rule:
• key : value → dictionary
• only values → set

Angle Brackets < >


Used internally by Python, not written by users.

Examples:
<class 'list'>
<class 'int'>

Purpose:
• Display type information
7. One-line Summary (Very Important)
[] → list / indexing / slicing
() → tuple / function calls / grouping
{} → dictionary or set
<> → internal type display

Choose the bracket based on data behavior, not appearance.


Python Detailed Notes (Day 1 to Day 10)

Overview
Days 1 to 10 focused on building a strong Python foundation through continuous practice.
The emphasis was on understanding how Python thinks, not just writing syntax.

Variables and Data Types


Variables store data in memory. Python is dynamically typed, meaning you don’t need to
declare the type explicitly. Common data types include int, float, string, bool.

Example:
age = 19 # int
price = 99.5 # float
name = 'Shubham' # string

Input and Type Conversion


The input() function always returns a string. To perform calculations, we convert it using
int() or float().

Example:
age = int(input('Enter age: '))

Conditional Statements
if, elif, else control program flow based on conditions. Python uses indentation instead of
braces to define blocks.

Example:
if age >= 18:
print('Eligible')
else:
print('Not eligible')

Loops
for loops are used when the number of iterations is known. while loops are used when the
number of iterations depends on a condition.

break exits the loop completely. continue skips the current iteration.

Data Structures
List: mutable, ordered collection.
Tuple: immutable, ordered collection.
Dictionary: key-value pairs.
Set: unordered collection of unique values.

Key Learning
By Day 10, you learned to combine logic, conditions, loops, and data structures to write
meaningful programs.
Mini Project Detailed Notes – Student Management System

Project Overview
The Student Management System project integrates Python fundamentals into a real-world
style application.

Data Design
Each student is represented as a dictionary. Multiple students are stored in a list. A set is
used to ensure unique student IDs.

Why while Loop Was Used


while loop allows retrying input when invalid data is entered, unlike for loop which runs a
fixed number of times.

Duplicate Handling
Student IDs are checked against a set before insertion. If duplicate is found, continue is used
to retry input.

Search Logic
A linear search is performed using a loop and a flag variable to determine whether a student
record exists.

Key Learning
This project teaches structured thinking, validation logic, and scalable program design.
Python Day 11 Detailed Notes – Functions

Introduction to Functions
Functions allow code reuse and help organize programs. They run only when called.

Function Definition
Functions are defined using def keyword. Indentation defines the function body.

Parameters and Arguments


Parameters receive values inside function definition. Arguments are actual values passed
during function call.

print vs return
print displays output to user. return sends value back to the program for reuse.

Boolean Functions
Functions can return True or False and be used directly inside if conditions.

not Operator
not inverts the boolean result after the function executes.

Key Learning
Day 11 builds the foundation for reusable, clean, and testable code.
Python Day 12 Detailed Notes – File Handling

Introduction to File Handling


File handling allows programs to store data permanently.

Opening Files
open(filename, mode) is used to access files. Modes include r, w, a.

Write Mode
w creates or overwrites a file. Old data is deleted.

Append Mode
a adds data at the end of file without deleting existing content.

Read Mode
r reads file content. Raises error if file does not exist.

Importance of close()
close() ensures data is saved and system resources are freed.

Key Learning
Programs can now persist data and retrieve it later.
Python Day 13 Detailed Notes – Error Handling & with Statement

1. What is Error Handling?


Error handling is a way to prevent a program from crashing when something goes wrong.
Users may enter wrong input or files may be missing. Instead of stopping the program,
Python allows handling such situations gracefully.

2. try and except Block


The try block contains code that might raise an error. If an error occurs, Python
immediately jumps to the except block. If no error occurs, except is skipped.

Example:
try:
num = int(input('Enter a number: '))
print(num)
except:
print('Invalid input')

3. Why Programs Should Not Crash


A crashing program looks unprofessional. Error handling ensures a better user experience
and stable programs.

4. File Handling Errors


Common file errors include missing files or permission issues. Without handling, Python
raises FileNotFoundError.

5. with open() Statement


with open() is a safer way to work with files. It automatically closes the file after use, even if
an error occurs.

Example:
with open('[Link]', 'r') as file:
print([Link]())

6. Combining try/except with with open()


Combining both ensures safe file operations. If the file does not exist, the program handles it
without crashing.

Example:
try:
with open('[Link]', 'r') as file:
print([Link]())
except:
print('File not found')

7. Key Takeaways
- Use try/except to handle errors
- Use with open() for file safety
- Never trust user input
- Professional programs never crash
Python Day 14 Detailed Notes – Modules & Imports

1. What is a Module?
A module is simply a Python file (.py) that contains code such as functions, variables, or
classes. Modules allow us to reuse code instead of writing the same logic again and again.

2. Why Modules Are Important


Modules help keep code organized, readable, and maintainable. In real projects, code is
divided into multiple modules instead of one large file.

3. Built-in Modules
Python provides many built-in modules like math and random. These modules contain
ready-made functions that save time and effort.

Examples:
- [Link]()
- [Link]
- [Link]()
- [Link]()

4. Import Styles
There are different ways to import modules:

1. import math
Access using [Link]()

2. from math import sqrt


Access directly using sqrt()

3. import math as m
Use alias [Link]()

5. Creating Your Own Module


You can create your own module by writing functions in a separate .py file. That file can
then be imported into another Python file.

6. __pycache__ Folder
Python automatically creates the __pycache__ folder to store compiled bytecode files (.pyc).
This improves performance. It is not mandatory and can be safely deleted; Python will
recreate it when needed.
7. Key Takeaways
- Modules help reuse and organize code
- Built-in modules provide ready tools
- Custom modules allow project structure
- __pycache__ is automatic and safe to ignore
Python Day 15 Detailed Notes – datetime Module

1. Why Programs Need Date and Time


Many real-world programs depend on dates and time. Examples include exam schedules,
expiry dates, deadlines, logging events, and timestamps. Python provides the datetime
module to handle such requirements.

2. Getting Current Date and Time


The datetime module contains a class also named datetime. Using [Link](),
we can get the current date and time.

Example:
import datetime
now = [Link]()
print(now)

3. Extracting Date and Time Parts


A datetime object stores year, month, day, hour, minute, and second. These parts can be
accessed using attributes like [Link] or [Link].

4. Formatting Date and Time (strftime)


strftime() converts a datetime object into a formatted string. This is useful for displaying
date and time in a user-friendly format.

Common format codes:


%Y – Year
%m – Month
%d – Day
%H – Hour (24-hour)
%M – Minute
%S – Second

5. Converting String to Date (strptime)


strptime() converts a date string into a datetime object. This allows comparison between
user-entered dates and current date.

Example:
date_obj = [Link]('2026-02-07', '%Y-%m-%d')

6. Comparing Dates
Date comparison works only when both values are datetime objects. You can compare using
<, >, or == operators.
Important note:
Comparing full datetime objects includes time. To compare only dates, use .date() method.

7. Key Takeaways
- datetime module handles date and time
- now() gives current date and time
- strftime() formats datetime
- strptime() converts string to datetime
- Date comparison is useful for real-world logic
Python Day 16 – Detailed Notes

1. What We Learned Today


Day 16 focused on combining Python data structures. Instead of using only lists or only
dictionaries, we learned how to use them together to store and manage real-world data.

2. List of Dictionaries
A list of dictionaries is used when we have multiple records of the same type. Each
dictionary represents one record, and the list holds all records together.

Example:
students = [
{'id': '001', 'name': 'Amit', 'age': 20},
{'id': '002', 'name': 'Ravi', 'age': 22}
]

3. Looping Through a List of Dictionaries


When we loop through a list, Python gives one element at a time. If the list elements are
dictionaries, the loop variable becomes a dictionary.

Example:
for student in students:
print(student['name'])

4. Searching Data
Searching is done by looping through the list and comparing a value from each dictionary. A
flag variable like 'found' is used to track whether the record exists.

Important rule: Do NOT print 'not found' inside the loop. Always decide after the loop
finishes.

5. Updating Data
Dictionaries are mutable. When we modify a dictionary inside a loop, the change affects the
original data stored in the list.

Example:
if student['id'] == search_id:
student['age'] = new_age

6. ID Handling Best Practice


IDs should be stored as strings, not integers. This avoids errors with leading zeros like '001'
and matches real-world systems.
7. Common Mistakes to Avoid
- Printing 'not found' inside loops
- Using integers for IDs with leading zeros
- Mixing multiple concepts in one file
- Forgetting to use a flag variable

8. Key Takeaways
- Lists store multiple items
- Dictionaries store meaningful data
- List of dictionaries is a powerful pattern
- Loop → search → update is core backend logic
Python Day 17 – Detailed Notes

1. Core Focus of Day 17


Day 17 focused on combining functions with complex data structures like lists of
dictionaries. The goal was to structure code in a modular way similar to real-world backend
systems.

2. Functions Working with Data Structures


Instead of writing logic directly in the main program, we created functions that accept
structured data (like a list of dictionaries) and operate on it.

Example structure:
employees = [
{'emp_id': '001', 'name': 'Shubham', 'age': 25},
{'emp_id': '002', 'name': 'Love', 'age': 20}
]

3. Passing Data into Functions


A function must receive all the information it needs through parameters. It should not
depend on global variables.

Display function needs only the list.


Search function needs the list and the search ID.
Update function needs the list, search ID, and new value.

4. Search Logic Pattern


Searching inside a list of dictionaries follows this pattern:
- Use a loop
- Compare the key value
- Use a flag variable (found = False)
- Break when found
- Print 'not found' after the loop

5. Update Logic Pattern


Dictionaries are mutable. When modified inside a loop, the original data inside the list is
updated directly.

Example:
if student['student_id'] == search_id:
student['age'] = new_age
6. Function Responsibility Principle
Each function should do only one job:
- display_all() → shows data
- search_student() → finds data
- update_student_age() → modifies data

7. Clean Architecture Concept


Separating user input from logic makes the code reusable, testable, and easier to maintain.

8. Common Mistakes to Avoid


- Printing 'not found' inside the loop
- Forgetting to use a flag variable
- Depending on global variables inside functions
- Mixing display, search, and update logic in one function

9. Key Takeaways
- Functions increase modularity
- Data structures store structured information
- Passing parameters controls data flow
- Loop + condition + flag is a core backend pattern
- Clean separation improves professional coding style
Python Day 18 - Detailed Notes

1. Print vs Return
print() is used to display output on the screen.

return is used to send a value back to the caller of the function.

A function that uses print() cannot reuse its result in other operations.

A function that uses return allows storing, comparing, modifying, or passing the result
further.

Professional code prefers return for logic and print for display only.

2. Returning Calculated Values (Average Example)


To calculate average of a list:

Average = sum(list) / len(list)

sum() calculates total of elements.

len() gives total number of elements.

Returning the average allows further comparisons or calculations.

3. Returning Dictionaries from Functions


Functions can create and return dictionaries.

This helps in structured data handling.

Returned dictionary can be accessed using keys outside the function.

4. Returning Updated Lists


Lists are mutable, so they update directly.

However, returning the updated list improves clarity and avoids hidden side effects.

It makes data flow visible and code more professional.

5. Filtering Data (Collecting Results in Loop)


When filtering items, never return inside the loop immediately.

Instead follow this structure:

1. Create empty list.

2. Loop through data.


3. Append matching items.

4. Return the new list after loop finishes.

Returning a new list preserves original data.

6. Tracking Maximum Value (Topper Logic)


To find highest value in structured data:

1. Assume first element is maximum.

2. Loop through remaining elements.

3. Compare current value with stored maximum.

4. If larger, update maximum.

5. Return final maximum after loop.

This is called maximum tracking pattern and is widely used in programming.

7. Important Programming Principles Learned


- Avoid returning inside loop unless intentional.

- Prefer returning data instead of printing inside functions.

- Avoid hidden modifications (side effects).

- Write logic in steps before coding.

- Think like a system designer, not just a coder.


Python Day 19 – Detailed Notes

1. Lambda Functions (Anonymous Functions)


Lambda functions are small, one-line functions without a name. They are mainly used when
a function is needed temporarily for a short operation.

Syntax: lambda arguments: expression

Example: square = lambda x: x * x

Lambda functions are commonly used with functions like sorted(), map(), filter(), min(),
and max.

2. Difference Between def and lambda


def: Used for full functions with multiple statements.

lambda: Used for short single-expression functions.

Lambda functions automatically return the result of the expression.

3. Sorting Lists Using sorted()


The sorted() function returns a new sorted list without modifying the original list.

Example: sorted(numbers)

There is another method [Link]() which modifies the original list directly.

4. Sorting in Reverse Order


To sort a list in descending order, Python provides the parameter reverse=True.

Example: sorted(numbers, reverse=True)

5. Sorting Dictionaries
Python cannot directly sort dictionaries inside a list because it does not know which field to
compare.

We solve this by using the key parameter to specify which value should be used for sorting.

Example: sorted(students, key=lambda student: student['marks'])

6. Using Lambda with Sorting


Lambda helps extract the field value from each dictionary so Python knows what value to
compare.

Example: key=lambda student: student['marks'] means 'use marks value for sorting'.
7. List Slicing
Python allows selecting a part of a list using slicing.

Syntax: list[start:end]

The start index is included, but the end index is not included.

Example: list[:2] returns elements at index 0 and 1.

8. Real Use Case (Top Students Example)


By sorting students by marks in descending order and selecting the first two elements using
slicing, we can easily find the top students.

9. Key Programming Concepts Learned


- Lambda functions for temporary logic

- Sorting lists safely using sorted()

- Sorting complex data using key functions

- Reverse sorting using reverse=True

- Extracting top elements using slicing


Python Day 20 – map() and filter() Detailed Notes

1. Introduction to Functional Tools


In Python, map() and filter() are functional programming tools used to process collections
of data efficiently.

map() → transforms every element in a sequence

filter() → keeps only elements that satisfy a condition

Both return iterator objects (map object or filter object), so we usually convert them to a list
using list().

2. map() Function
map() applies a function to every element of an iterable (like a list).

Syntax:

map(function, iterable)

Example:

numbers = [1,2,3,4]

squares = list(map(lambda x: x*x, numbers))

Result:

[1,4,9,16]

Here lambda x: x*x is applied to every number in the list.

3. Why list() is Used with map()


map() returns a map object (iterator).
Example without list():

squares = map(lambda x: x*x, numbers)

print(squares)

Output:

<map object at 0x...>

To see actual values we convert it:

list(map(...))

4. filter() Function
filter() keeps only elements that satisfy a condition.

Syntax:

filter(function, iterable)

The function must return True or False.

Example:

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

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))


Result:

[2,4,6]

5. Why list() is Used with filter()


filter() returns a filter object (iterator).

Example without list():

even_numbers = filter(lambda x: x % 2 == 0, numbers)

print(even_numbers)

Output:

<filter object at 0x...>

To see actual elements we convert it to list.

6. Using map() with Dictionaries


map() can transform data from dictionaries.

Example:

students = [

{"name":"A","marks":75},

{"name":"B","marks":40},

{"name":"C","marks":85}

names = list(map(lambda s: s["name"], students))


Result:

['A','B','C']

Here each dictionary is processed and only the 'name' field is extracted.

7. Using filter() with Dictionaries


filter() can remove dictionaries based on conditions.

Example:

students = [

{"name":"A","marks":75},

{"name":"B","marks":40},

{"name":"C","marks":85},

{"name":"D","marks":35}

passed_students = list(filter(lambda s: s["marks"] >= 50, students))

Result:

[{'name':'A','marks':75}, {'name':'C','marks':85}]

8. Difference Between map() and filter()


map() → modifies or transforms elements

filter() → removes elements based on condition

Example:

map → convert numbers to squares


filter → keep only even numbers

9. Practical Use Cases


map():

- Convert strings to integers

- Convert names to uppercase

- Increase salaries

- Transform values in a list

filter():

- Remove failed students

- Keep only even numbers

- Filter valid data

- Remove unwanted records

10. Key Takeaways


• map() transforms every element

• filter() keeps elements based on condition

• Both return iterator objects

• list() is used to convert results into a visible list

• Works well with lists, tuples, and dictionaries


Python Day 21 – List Comprehension (Detailed Notes)

1. What is List Comprehension?


List comprehension is a shorter and cleaner way to create lists in Python using a single line
of code. It replaces many cases where we normally use loops with append().

2. Basic Syntax
new_list = [expression for item in iterable]

Example:

numbers = [1,2,3,4]

squares = [x*x for x in numbers]

Result: [1,4,9,16]

3. Equivalent Loop Version


squares = []

for x in numbers:

[Link](x*x)

This shows how list comprehension internally works.

4. List Comprehension with Condition


You can add a condition to filter elements.

Example:

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

even_numbers = [x for x in numbers if x % 2 == 0]

Result: [2,4,6]

5. Using List Comprehension with Dictionaries


Example:

students = [

{'name':'A','marks':45},

{'name':'B','marks':75},

{'name':'C','marks':35},
{'name':'D','marks':80}

passed_students = [s for s in students if s['marks'] >= 50]

Result: [{'name': 'B', 'marks': 75}, {'name': 'D', 'marks': 80}]

6. Why Developers Use List Comprehension


- Code becomes shorter

- Code becomes easier to read

- Faster than traditional loops

- Very common in real Python projects

7. Key Things to Remember


- x represents each element of the list

- 'for x in numbers' means looping through the list

- 'if condition' filters elements

- The result is always a new list


Python Day 22 – Advanced Dictionary Operations

1. Dictionary Keys
keys() returns all the keys of a dictionary.

Example:

student = {'name':'Shubham','age':20,'course':'BCA'}

[Link]()

Output: dict_keys(['name','age','course'])

Keys represent the field names of the dictionary.

2. Dictionary Values
values() returns all the values of a dictionary.

Example:

[Link]()

Output: dict_values(['Shubham',20,'BCA'])

Values represent the actual stored data.

3. Dictionary Items
items() returns key-value pairs together.

Example:

[Link]()

Output: dict_items([('name','Shubham'),('age',20),('course','BCA')])

This method is very useful when looping through dictionaries.

4. Looping Through Dictionary


Example:

for key,value in [Link]():

print(key,':',value)

Output:

name : Shubham
age : 20

course : BCA

5. Dictionary Comprehension
Dictionary comprehension creates dictionaries using a single line.

Example:

numbers=[1,2,3,4]

square_dict={x:x*x for x in numbers}

Output: {1:1,2:4,3:9,4:16}

6. Filtering Dictionary
You can apply conditions inside dictionary comprehension.

Example:

marks={'Math':85,'English':45,'Science':78,'History':30}

passed={k:v for k,v in [Link]() if v>=50}

Output: {'Math':85,'Science':78}

7. Reversing Dictionary
You can swap keys and values.

Example:

student={'name':'Shubham','course':'BCA','city':'Delhi'}

rev={v:k for k,v in [Link]()}

Output: {'Shubham':'name','BCA':'course','Delhi':'city'}

Note: values must be unique when reversing dictionaries.

8. Key Takeaways
- keys() → returns dictionary keys

- values() → returns dictionary values

- items() → returns key-value pairs

- dictionary comprehension helps build dictionaries quickly

- filtering and reversing dictionaries are common real-world tasks

You might also like