Python Notes
Python Notes
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).
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
9. type() Function
• type() shows data type.
• Output format:
<class 'str'>
<class 'int'>
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
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
Correct example:
if marks >= 90:
print('A')
elif marks >= 75:
print('B')
elif marks >= 50:
print('C')
else:
print('Fail')
Logical Bug:
• Code runs but gives wrong output
• Usually caused by wrong condition order
2. Boolean Values
Boolean values represent truth values:
• True
• 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')
Example:
is_admin = False
Meaning: 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
Example:
has_id = input('Do you have ID? ').strip().lower()
This handles:
YES, Yes, yes, yEs
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.
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
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
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.
Flow:
i = 1 → j runs 1 to 3
i = 2 → j runs 1 to 3
i = 3 → j runs 1 to 3
Rules:
• Outer loop controls rows
• Inner loop controls columns (items in a row)
• Inner loop usually depends on outer loop variable
Example:
print('*', end=' ')
print() # moves to next line
Output:
*
**
***
****
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()
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.
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.
Example:
for num in numbers:
print(num)
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
Example:
name = 'Python'
name = name[:2] + 'k' + name[3:]
Result: 'Pykhon'
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
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
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
Example:
names = ('Amit', 'Ravi', 'Sita')
names[0] → 'Amit'
names[-1] → 'Sita'
4. Tuple Immutability
Tuple elements cannot be modified.
Example:
nums = (10, 20, 30)
nums[1] = 99 → TypeError
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
student['age'] = 22 # update
student['city'] = 'Mumbai' # add
Example:
List: ['Amit', 21, 85] # unclear
Dictionary: {'name':'Amit','age':21,'marks':85} # clear
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}
Adding an element:
[Link]('orange')
Removing an element:
[Link]('banana')
Example:
if 'apple' in values:
print('Present')
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
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
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.
Example:
age = 19 # int
price = 99.5 # float
name = 'Shubham' # string
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.
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.
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
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
Example:
try:
num = int(input('Enter a number: '))
print(num)
except:
print('Invalid input')
Example:
with open('[Link]', 'r') as file:
print([Link]())
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.
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]()
3. import math as m
Use alias [Link]()
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
Example:
import datetime
now = [Link]()
print(now)
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
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}
]
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
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
Example structure:
employees = [
{'emp_id': '001', 'name': 'Shubham', 'age': 25},
{'emp_id': '002', 'name': 'Love', 'age': 20}
]
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
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.
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.
However, returning the updated list improves clarity and avoids hidden side effects.
Lambda functions are commonly used with functions like sorted(), map(), filter(), min(),
and max.
Example: sorted(numbers)
There is another method [Link]() which modifies the original list directly.
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: 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.
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]
Result:
[1,4,9,16]
print(squares)
Output:
list(map(...))
4. filter() Function
filter() keeps only elements that satisfy a condition.
Syntax:
filter(function, iterable)
Example:
numbers = [1,2,3,4,5,6]
[2,4,6]
print(even_numbers)
Output:
Example:
students = [
{"name":"A","marks":75},
{"name":"B","marks":40},
{"name":"C","marks":85}
['A','B','C']
Here each dictionary is processed and only the 'name' field is extracted.
Example:
students = [
{"name":"A","marks":75},
{"name":"B","marks":40},
{"name":"C","marks":85},
{"name":"D","marks":35}
Result:
[{'name':'A','marks':75}, {'name':'C','marks':85}]
Example:
- Increase salaries
filter():
2. Basic Syntax
new_list = [expression for item in iterable]
Example:
numbers = [1,2,3,4]
Result: [1,4,9,16]
for x in numbers:
[Link](x*x)
Example:
numbers = [1,2,3,4,5,6]
Result: [2,4,6]
students = [
{'name':'A','marks':45},
{'name':'B','marks':75},
{'name':'C','marks':35},
{'name':'D','marks':80}
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'])
2. Dictionary Values
values() returns all the values of a dictionary.
Example:
[Link]()
Output: dict_values(['Shubham',20,'BCA'])
3. Dictionary Items
items() returns key-value pairs together.
Example:
[Link]()
Output: dict_items([('name','Shubham'),('age',20),('course','BCA')])
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]
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}
Output: {'Math':85,'Science':78}
7. Reversing Dictionary
You can swap keys and values.
Example:
student={'name':'Shubham','course':'BCA','city':'Delhi'}
Output: {'Shubham':'name','BCA':'course','Delhi':'city'}
8. Key Takeaways
- keys() → returns dictionary keys