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

python

The document provides a structured introduction to Python programming over six days, covering installation, variables, data types, operators, conditional statements, loops, and functions. Each day includes practical tasks and examples to reinforce learning, with comparisons to C/C++ to aid understanding. The content is designed for beginners and emphasizes Python's simplicity and powerful features.
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 views94 pages

python

The document provides a structured introduction to Python programming over six days, covering installation, variables, data types, operators, conditional statements, loops, and functions. Each day includes practical tasks and examples to reinforce learning, with comparisons to C/C++ to aid understanding. The content is designed for beginners and emphasizes Python's simplicity and powerful features.
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
You are on page 1/ 94

Day 1: Introduction to Python & Installing It

🔹 What is Python?

Python is a programming language used to build websites, automate tasks, analyze data, and
more. It's popular because it's simple and powerful.

🔹 What You Need Today:

• Install Python
• Set up a code editor

Task for Today:

1. Install Python

• Go to: https://www.python.org/downloads
• Download the latest version for your operating system
• During installation, make sure to check the box that says: “Add Python to PATH”

2. Install a Code Editor (Optional but Recommended)

Choose one:

• VS Code: https://code.visualstudio.com
• Thonny (Beginner-friendly): https://thonny.org

3. Try Your First Python Program

After installation, open the Python shell or your editor and type:

python
CopyEdit
print("Hello, Python!")

If it prints Hello, Python!, you're all set!

Let me know once you're done. Tomorrow, we’ll start with Variables and Data Types.

You said:
Explain every topics deeply next topic explain deeply
ChatGPT said:

Perfect! Since you've completed Day 1, let’s move on to:

📘 Day 2: Variables and Data Types in Python

What is a Variable?

A variable is a name that stores a value. Think of it as a container in memory where data is kept.

Example:
python
CopyEdit
name = "Alice"
age = 25

Here:

• name is a variable that holds a string value "Alice"


• age holds an integer value 25

Rules for Naming Variables

• Must start with a letter or underscore (_)


• Can contain letters, numbers, and underscores
• Cannot start with a number
• Cannot use Python keywords (like if, while, for, etc.)

Valid Examples:

python
CopyEdit
x = 10
user_name = "John"
_age = 30

Invalid Examples:

python
CopyEdit
2x = 10 # Starts with a number
user-name = "Alice" # Hyphen not allowed
if = 5 # 'if' is a keyword
🔹 Data Types in Python

Python has several built-in data types. Let’s explore the most basic ones:

1. String (str) — Text data


python
CopyEdit
name = "Alice"
message = 'Hello, World!'

2. Integer (int) — Whole numbers


python
CopyEdit
age = 25
year = 2025

3. Float (float) — Decimal numbers


python
CopyEdit
height = 5.9
price = 99.99

4. Boolean (bool) — True or False


python
CopyEdit
is_adult = True
has_license = False

🔹 Type Checking

You can check the type of any variable using type():

python
CopyEdit
name = "Alice"
print(type(name)) # Output: <class 'str'>

age = 25
print(type(age)) # Output: <class 'int'>

🧠 Practice Task for Today

Try this small Python script:


python
CopyEdit
# Define variables
first_name = "John"
last_name = "Doe"
age = 22
height = 5.8
is_student = True

# Print variable types


print("Name:", first_name, last_name)
print("Age:", age)
print("Height:", height)
print("Is a student:", is_student)

# Check types
print(type(first_name))
print(type(age))
print(type(height))
print(type(is_student))

Let me know once you complete this.


Tomorrow’s Topic: Operators in Python (Arithmetic, Comparison, Logical, etc.)

You said:
Operater deeply I have knowledge of cpp and c

ChatGPT said:

Great! Since you already know C and C++, you're in a good position to understand Python
operators more easily. Let's dive into them deeply and also note the differences where relevant.

📘 Day 3: Operators in Python (Deep Dive)

In Python, operators are special symbols used to perform operations on variables and values.

🔹 1. Arithmetic Operators

Same as in C/C++, but Python has some extras like // (floor division) and ** (exponentiation).

Operator Description Example Output

+ Addition 10 + 5 15

- Subtraction 10 - 5 5
Operator Description Example Output

* Multiplication 10 * 5 50

/ Division (float) 10 / 3 3.333

// Floor Division 10 // 3 3

% Modulus 10 % 3 1

** Exponent (power) 2 ** 3 8

Difference from C/C++:


/ always returns a float in Python, even if divisible. 10 / 2 → 5.0 not 5

🔹 2. Assignment Operators
Operator Meaning Example Same as

= Assign value x = 5 —

+= Add and assign x += 3 x = x + 3

-= Subtract x -= 2 x = x - 2

*= Multiply x *= 2 x = x * 2

/= Divide x /= 2 x = x / 2

//= Floor divide x //= 2 x = x // 2

%= Modulo x %= 2 x = x % 2

**= Exponent x **= 2 x = x ** 2

🔹 3. Comparison (Relational) Operators

Just like in C/C++, these return Boolean values (True or False).

Operator Meaning Example Output

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True


Operator Meaning Example Output

> Greater than 5 > 3 True

< Less than 5 < 3 False

>= Greater or equal 5 >= 5 True

<= Less or equal 5 <= 4 False

🔹 4. Logical Operators

Work with Boolean values, similar to &&, ||, ! in C++.

Operator Meaning Example Output

and Logical AND True and False False

or Logical OR True or False True

not Logical NOT not True False

Python uses plain English words instead of symbols (&&, ||, !) like in C/C++.

🔹 5. Identity Operators

These check if two variables refer to the same object in memory.

Operator Meaning Example Output

is Same object? a is b True/False

is not Not same object? a is not b True/False

python
CopyEdit
a = [1, 2]
b = a # b points to same list
print(a is b) # True
print(a == b) # True (same content)
🔹 6. Membership Operators

Used to test if a value is in a sequence (like string, list, etc.)

Operator Meaning Example Output

in Value found in object "a" in "apple" True

not in Value not found "x" not in "apple" True

🧠 Practice Task for Today:

Try this code:

python
CopyEdit
a = 10
b = 3

# Arithmetic
print("Addition:", a + b)
print("Division (float):", a / b)
print("Division (floor):", a // b)
print("Power:", a ** b)

# Comparison
print("Is a equal to b?", a == b)
print("Is a greater than b?", a > b)

# Logical
x = True
y = False
print("x and y:", x and y)
print("x or y:", x or y)
print("not x:", not x)

# Membership
print("p" in "python")
print("z" not in "python")

Let me know when you're ready.


Tomorrow’s Topic: Conditional Statements (if, elif, else) in Python – with examples and
differences from C/C++.

You said:
Explain deeply conditionals
ChatGPT said:

Excellent! Let's move on to:

📘 Day 4: Conditional Statements in Python (Deep & Practical)

Conditional statements let your program make decisions based on whether conditions are True
or False—just like in C/C++, but with a cleaner syntax.

Python Conditional Keywords:

• if
• elif (short for "else if")
• else

🔸 1. Basic if Statement
python
CopyEdit
age = 18

if age >= 18:


print("You are an adult.")

Syntax Breakdown:

• No parentheses around the condition (optional but not used by default).


• Colon (:) at the end of the condition line.
• Indentation (usually 4 spaces) is used to define blocks of code. No braces {} like in
C/C++.

🔸 2. if with else
python
CopyEdit
age = 16

if age >= 18:


print("Adult")
else:
print("Minor")
Comparison with C/C++:

C++:

cpp
CopyEdit
if (age >= 18) {
cout << "Adult";
} else {
cout << "Minor";
}

Python:

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

Simpler, right?

🔸 3. elif – Else If
python
CopyEdit
marks = 75

if marks >= 90:


print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Fail")

Python checks conditions top-down, and stops at the first True.

🔸 4. Nested Conditionals

Just like in C++, you can nest if statements.

python
CopyEdit
age = 20
citizen = True
if age >= 18:
if citizen:
print("Eligible to vote")
else:
print("Not a citizen")
else:
print("Underage")

Nested conditions are indented inside their parent block.

🔸 5. Short-hand (One-liner) Conditionals

One-line if:
python
CopyEdit
a = 10
if a > 5: print("a is greater than 5")

Ternary (Conditional Expression):


python
CopyEdit
age = 16
status = "Adult" if age >= 18 else "Minor"
print(status)

Similar to C++’s ternary operator: age >= 18 ? "Adult" : "Minor"

🔸 6. Boolean Logic in Conditions

You can use logical operators (and, or, not) directly:

python
CopyEdit
age = 20
has_id = True

if age >= 18 and has_id:


print("Entry allowed")
else:
print("Entry denied")
🔸 7. Common Mistakes to Avoid
Mistake Correct Version

Using () unnecessarily if x > 5: instead of if (x > 5):

Forgetting the colon : if x > 5 → if x > 5:

Not indenting Always indent the block under if, etc.

Mixing tabs and spaces in indent Use only spaces (4 spaces is standard)

🧠 Practice Task:

Try this:

python
CopyEdit
score = int(input("Enter your score (0–100): "))

if score > 100 or score < 0:


print("Invalid score")
elif score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Fail")

Let me know once you've completed the task.


Tomorrow’s Topic: Loops in Python (for, while) – with use cases and differences from
C/C++.

You said:
Loops

ChatGPT said:

Great! Today is:


📘 Day 5: Loops in Python (for and while) — Deep Dive

Loops let you repeat a block of code multiple times. Python supports two main types of loops:

• for loop
• while loop

There’s no do...while like in C/C++, but you can simulate it.

🔸 1. for Loop in Python

Python's for loop is different from C/C++:


Instead of using a counter (for(int i = 0; i < 10; i++)), Python’s for loop iterates over a
sequence (like a list, string, or range()).

Basic for loop using range():


python
CopyEdit
for i in range(5):
print(i)

Output:

CopyEdit
0
1
2
3
4

range(5) generates numbers from 0 to 4 (not including 5).

range(start, stop, step):

python
CopyEdit
for i in range(1, 10, 2):
print(i)

Output:

CopyEdit
1
3
5
7
9

Iterating over a list:


python
CopyEdit
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(fruit)

Iterating over a string:


python
CopyEdit
for letter in "Python":
print(letter)

🔸 2. while Loop in Python

while loops run as long as a condition is True, similar to C/C++.

python
CopyEdit
count = 0

while count < 5:


print(count)
count += 1

Output:

CopyEdit
0
1
2
3
4

🔸 3. Loop Control Statements


Statement Description

break Exit the loop completely


Statement Description

continue Skip the current iteration and continue

pass Do nothing (placeholder)

break example:
python
CopyEdit
for i in range(10):
if i == 5:
break
print(i)

Output: 0 1 2 3 4

continue example:
python
CopyEdit
for i in range(5):
if i == 2:
continue
print(i)

Output: 0 1 3 4

pass example (used for empty blocks):


python
CopyEdit
for i in range(3):
pass # Placeholder, does nothing

🔸 4. Else with Loops (Python-Specific Feature)

Python allows else with loops, which executes only if the loop didn’t break.

python
CopyEdit
for i in range(5):
print(i)
else:
print("Loop completed without break")

If you add a break, the else will not run.


🔸 5. Difference from C/C++:
Feature C/C++ Python

for syntax Uses 3-part loop (init; cond; inc) Iterates over sequences

Parentheses {} Required Not used, blocks use indentation

do...while Exists Not available (can be simulated)

else with loops Not supported Supported

🧠 Practice Tasks:

1. Use a for loop to print even numbers from 1 to 20.

2. Use a while loop to count down from 10 to 1.

3. Use break to exit a loop when a number is divisible by 7.

4. Use continue to skip printing vowels in a string.

Let me know when you've completed the tasks.


Tomorrow’s Topic: Functions in Python — declaration, parameters, return values, scope.

You said:
Explain deeply every things about the topic exp now function explain like Greek for Greek or w3

ChatGPT said:

Absolutely! Let’s go deep into Python functions — explained clearly and thoroughly, similar to
how you'd find on GeeksforGeeks or W3Schools, but tailored for you since you already know
C/C++.

📘 Day 6: Functions in Python — A Deep Dive

🔹 What is a Function?

A function is a reusable block of code that performs a specific task.


Why use functions?

• To organize code
• To avoid repetition
• To increase modularity
• To make debugging easier

🔹 Function Structure in Python


python
CopyEdit
def function_name(parameters):
# function body
return value

🔸 1. Defining a Function
python
CopyEdit
def greet():
print("Hello!")

def is the keyword used to define a function.

🔸 2. Calling a Function
python
CopyEdit
greet()

Output:

CopyEdit
Hello!

🔸 3. Function with Parameters


python
CopyEdit
def greet(name):
print("Hello,", name)

greet("Alice")

Output:

CopyEdit
Hello, Alice
🔸 4. Function with Return Value
python
CopyEdit
def add(a, b):
return a + b

result = add(3, 5)
print(result)

Output:

CopyEdit
8

In Python, return is used to send a value back to the caller.


If you don’t use return, the function returns None by default.

🔸 5. Default Parameters

You can give default values to parameters.

python
CopyEdit
def greet(name="Guest"):
print("Hello", name)

greet() # Hello Guest


greet("John") # Hello John

This avoids function overloading (like in C++). Instead of writing multiple versions, just use
default values.

🔸 6. Keyword vs Positional Arguments


python
CopyEdit
def info(name, age):
print(name, "is", age, "years old")

info("Alice", 25) # Positional


info(age=30, name="Bob") # Keyword
🔸 7. Variable-Length Arguments

*args → for multiple positional arguments


python
CopyEdit
def total(*numbers):
print(sum(numbers))

total(10, 20, 30) # 60

**kwargs → for multiple keyword arguments


python
CopyEdit
def show(**details):
for key, value in details.items():
print(key, ":", value)

show(name="Alice", age=25)

Output:

yaml
CopyEdit
name : Alice
age : 25

🔸 8. Return Multiple Values


python
CopyEdit
def stats(x, y):
return x+y, x*y

s, p = stats(3, 4)
print("Sum:", s, "Product:", p)

Python functions can return tuples — multiple values at once.

🔸 9. Scope of Variables
Scope Type Description

Local Declared inside a function

Global Declared outside all functions


Local Scope Example
python
CopyEdit
def func():
x = 10
print(x)

func()
print(x) # Error: x not defined outside

Global Scope Example


python
CopyEdit
x = 5

def show():
print(x)

show() # 5

Modifying Global Variable (using global)


python
CopyEdit
x = 5

def change():
global x
x = 10

change()
print(x) # 10

🔸 10. Anonymous Functions (Lambda)

One-line functions without names.


Used for short tasks.

python
CopyEdit
square = lambda x: x * x
print(square(5)) # 25

Equivalent to:

python
CopyEdit
def square(x):
return x * x

🔸 11. Function vs Method


Term Meaning

Function Defined using def, independent

Method A function attached to an object/class

python
CopyEdit
# Function
def greet():
print("Hello")

# Method (called on a string object)


"hello".upper() # HELLO

🔸 12. Docstrings (Documentation Strings)

Python allows inline documentation inside functions.

python
CopyEdit
def square(n):
"""Returns the square of a number"""
return n * n

print(square.__doc__)

Output:

css
CopyEdit
Returns the square of a number

🧠 Practice Tasks:

1. Write a function is_even(n) that returns True if n is even.


2. Write a function factorial(n) that uses a loop.
3. Write a function greet(name="User") with a default argument.
4. Write a function that takes any number of arguments and returns the average.
5. Use lambda to create a function that returns the cube of a number.
Let me know once you're done.
Tomorrow’s Topic: Lists in Python – creation, operations, indexing, slicing, methods, with
deep examples.

You said:
Continue

ChatGPT said:

Great! Let’s move on to:

📘 Day 7: Lists in Python — Complete Deep Dive

Lists are one of the most used data structures in Python. They're ordered, mutable, and can
store heterogeneous data (unlike arrays in C++ which hold only one type).

🔹 1. Creating a List
python
CopyEdit
fruits = ["apple", "banana", "cherry"]

Lists are created using square brackets [].

You can store:

• Strings
• Numbers
• Other lists
• Mixed types

python
CopyEdit
my_list = [1, "hello", 3.14, [10, 20]]

🔹 2. Accessing Elements

Same as in C++, using zero-based indexing:

python
CopyEdit
print(fruits[0]) # apple
print(fruits[2]) # cherry
Negative indexing:

python
CopyEdit
print(fruits[-1]) # cherry (last)
print(fruits[-2]) # banana

🔹 3. List Slicing
python
CopyEdit
numbers = [0, 1, 2, 3, 4, 5]

print(numbers[1:4]) # [1, 2, 3]
print(numbers[:3]) # [0, 1, 2]
print(numbers[3:]) # [3, 4, 5]
print(numbers[-3:]) # [3, 4, 5]

list[start:stop] includes start but excludes stop.

🔹 4. Modifying Elements
python
CopyEdit
fruits[1] = "orange"
print(fruits) # ['apple', 'orange', 'cherry']

Lists are mutable, unlike strings or tuples.

🔹 5. List Methods (Built-in)


Method Description

append(x) Adds x to the end of the list

insert(i, x) Inserts x at index i

remove(x) Removes first occurrence of x

pop() Removes and returns last item

pop(i) Removes and returns item at index i

clear() Removes all items

index(x) Returns index of first x


Method Description

count(x) Counts how many times x appears

sort() Sorts the list (ascending)

reverse() Reverses the list in-place

copy() Returns a shallow copy

Examples:
python
CopyEdit
fruits = ["banana", "apple", "cherry"]

fruits.append("orange")
fruits.sort()
fruits.remove("banana")
print(fruits)

Output:

css
CopyEdit
['apple', 'cherry', 'orange']

🔹 6. Looping Through Lists


python
CopyEdit
for fruit in fruits:
print(fruit)

Using index:

python
CopyEdit
for i in range(len(fruits)):
print(i, fruits[i])

🔹 7. List Comprehension (Pythonic Shortcut)

A powerful one-liner to create lists.

python
CopyEdit
squares = [x*x for x in range(6)]
print(squares) # [0, 1, 4, 9, 16, 25]
With conditions:

python
CopyEdit
evens = [x for x in range(10) if x % 2 == 0]

🔹 8. Membership Testing
python
CopyEdit
print("apple" in fruits) # True
print("mango" not in fruits) # True

🔹 9. Nested Lists (2D Lists)


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

print(matrix[0][1]) # 2

🔹 10. Built-in Functions with Lists


Function Description

len(lst) Number of items

max(lst) Largest item

min(lst) Smallest item

sum(lst) Sum of all items (numbers only)

🧠 Practice Tasks:

1. Create a list of 5 numbers and print their sum.


2. Write a list comprehension that creates a list of squares from 1 to 10.
3. Given a list of names, remove all names that start with 'A'.
4. Reverse a list without using reverse().
5. Create a 3x3 matrix and access the middle element.
Let me know when you complete the tasks.
Tomorrow’s Topic: Tuples — immutable lists, when and why to use them, with examples
and comparisons to lists.

You said:
Continue

ChatGPT said:

Awesome! Let’s continue your journey in Python with:

📘 Day 8: Tuples in Python — Full Deep Dive

Tuples are very similar to lists, but they are immutable (they can’t be changed once created).
This makes them:

• Faster than lists


• Safer for fixed data
• Hashable (can be used as dictionary keys or in sets)

🔹 1. What is a Tuple?

A tuple is a collection of ordered elements, defined with parentheses ().

python
CopyEdit
my_tuple = (10, 20, 30)

You can also create a tuple without parentheses:

python
CopyEdit
t = 1, 2, 3

It’s still a tuple!

🔸 2. Single-Element Tuple — The Trap!

Just putting one value in parentheses is not enough:

python
CopyEdit
t = (5)
print(type(t)) # ➤ int

Correct:

python
CopyEdit
t = (5,)
print(type(t)) # ➤ tuple

The comma makes it a tuple, not the parentheses.

🔸 3. Accessing Tuple Elements

Just like lists — indexing and slicing work the same:

python
CopyEdit
t = ("a", "b", "c", "d")

print(t[0]) # a
print(t[-1]) # d
print(t[1:3]) # ('b', 'c')

🔸 4. Why Use Tuples Over Lists?


Feature List ([]) Tuple (())

Mutable Yes No

Faster Slower Faster

Hashable No Yes

Safer Can be modified Cannot be modified

🔸 5. Tuple Operations

Concatenation:
python
CopyEdit
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2 # (1, 2, 3, 4)
Repetition:
python
CopyEdit
t = (1, 2)
print(t * 3) # (1, 2, 1, 2, 1, 2)

Membership:
python
CopyEdit
print(3 in (1, 2, 3)) # True

Iteration:
python
CopyEdit
for x in (10, 20, 30):
print(x)

🔸 6. Tuple Methods
Method Description

count(x) Returns number of times x appears

index(x) Returns the first index of x

python
CopyEdit
t = (1, 2, 3, 2, 2)

print(t.count(2)) # 3
print(t.index(3)) # 2

🔸 7. Tuple Unpacking

You can assign tuple values to variables directly:

python
CopyEdit
point = (10, 20)

x, y = point
print(x) # 10
print(y) # 20

Must match the number of values


python
CopyEdit
a, b, c = (1, 2, 3) # OK
a, b = (1, 2, 3) # Error!

🔸 8. Nested Tuples
python
CopyEdit
nested = ((1, 2), (3, 4))

print(nested[1][0]) # 3

🔸 9. Using Tuples in Dictionaries (Hashable)

Unlike lists, tuples can be keys in dictionaries:

python
CopyEdit
locations = {
(0, 0): "origin",
(1, 2): "point A"
}

🔸 10. When to Use Tuples

• When the data should not change


• For fixed-size records (like coordinates, RGB values)
• As dictionary keys or in sets
• For better performance

🧠 Practice Tasks:

1. Create a tuple with the first 5 even numbers.


2. Unpack a tuple (name, age, country) into 3 variables.
3. Find how many times 7 occurs in (1, 7, 7, 3, 4).
4. Write a tuple of 3 RGB values and print the green one.
5. Try to modify a tuple element and observe the error.

Let me know when you're done.


Tomorrow’s Topic: Dictionaries in Python — key-value pairs, methods, looping, nesting,
use cases.
You said:
Continue

ChatGPT said:

Excellent! Let's move on to another foundational data structure in Python:

📘 Day 9: Dictionaries in Python — Deep Dive

A dictionary in Python is an unordered collection of key-value pairs.


Think of it like a real-life dictionary where you look up a word (key) to get its definition
(value).

🔹 1. Creating a Dictionary
python
CopyEdit
student = {
"name": "Alice",
"age": 20,
"marks": 85
}

• Keys must be unique and immutable (strings, numbers, or tuples).


• Values can be any data type (even lists, other dictionaries).

🔹 2. Accessing Values
python
CopyEdit
print(student["name"]) # Alice
print(student["marks"]) # 85

If the key doesn't exist → KeyError

Safer method:

python
CopyEdit
print(student.get("grade", "Not Found")) # Not Found
🔹 3. Adding & Updating Values

Add a new key-value:


python
CopyEdit
student["grade"] = "A"

Update existing:
python
CopyEdit
student["marks"] = 90

🔹 4. Removing Key-Value Pairs


Method Description

del dict[key] Deletes specific key

dict.pop(key) Removes key and returns value

dict.clear() Empties the whole dictionary

python
CopyEdit
del student["age"]
student.pop("marks")
student.clear() # makes it {}

🔹 5. Looping Through a Dictionary

Keys:
python
CopyEdit
for key in student:
print(key)

Keys + Values:
python
CopyEdit
for key, value in student.items():
print(key, "=>", value)

Values only:
python
CopyEdit
for value in student.values():
print(value)

🔹 6. Common Dictionary Methods


Method Description

dict.keys() Returns all keys

dict.values() Returns all values

dict.items() Returns all (key, value) pairs

dict.get(key) Returns value or None/default

dict.update(dict2) Adds or updates keys from another dict

🔹 7. Check Existence of Key


python
CopyEdit
if "name" in student:
print("Name is available")

🔹 8. Nested Dictionaries

You can store dictionaries inside other dictionaries:

python
CopyEdit
students = {
"s1": {"name": "Alice", "marks": 90},
"s2": {"name": "Bob", "marks": 85}
}

print(students["s1"]["marks"]) # 90

🔹 9. Use Case Examples

• Store user profiles


• Frequency counters
• Grouping data
• JSON-like structures for web apps
🔹 10. Dictionary Comprehension (Pythonic Style)
python
CopyEdit
squares = {x: x*x for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

With condition:

python
CopyEdit
even_squares = {x: x*x for x in range(10) if x % 2 == 0}

🧠 Practice Tasks:

1. Create a dictionary for a book with keys: title, author, price.


2. Add a new key publisher, then update the price.
3. Loop through a dictionary and print keys with values.
4. Store marks of 3 students in a nested dictionary.
5. Use comprehension to map each character in "hello" to its ASCII value.

Let me know once you're done.


Tomorrow’s Topic: Sets in Python — properties, operations (union, intersection), use
cases, and differences from lists.

You said:
Continue

ChatGPT said:

Great! You're doing an excellent job progressing through Python fundamentals.


Today, we’ll explore a very powerful and often underused data structure:

📘 Day 10: Sets in Python — Complete Deep Dive

A set in Python is an unordered, unindexed collection of unique elements.

Key Properties:

• No duplicate values
• Unordered: No guarantee of element position
• Elements must be immutable (like numbers, strings, tuples)
🔹 1. Creating a Set
python
CopyEdit
my_set = {1, 2, 3}
print(my_set)

If you want to create an empty set:

python
CopyEdit
empty_set = set() # NOT {}

{} creates an empty dictionary.

🔹 2. No Duplicates Allowed
python
CopyEdit
nums = {1, 2, 2, 3, 4}
print(nums) # {1, 2, 3, 4}

Python automatically removes duplicates.

🔹 3. Set Elements Must Be Immutable

These work:

python
CopyEdit
{1, "hello", (3, 4)}

This fails:

python
CopyEdit
{[1, 2]} # TypeError: unhashable type: 'list'

🔹 4. Adding and Removing Elements

add() – Adds one item:


python
CopyEdit
s = {1, 2}
s.add(3) # {1, 2, 3}

update() – Adds multiple items:


python
CopyEdit
s.update([4, 5], {6, 7})

remove() vs discard()
python
CopyEdit
s.remove(4) # Error if not found
s.discard(4) # No error if not found

pop() removes a random item:


python
CopyEdit
s.pop()

🔹 5. Set Operations (Mathematical Style)

Let’s use these sets:

python
CopyEdit
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
Operation Code Result

Union `a bora.union(b)`

Intersection a & b or a.intersection(b) {3, 4}

Difference (a - b) a - b or a.difference(b) {1, 2}

Symmetric Difference a ^ b or a.symmetric_difference(b) {1, 2, 5, 6}

🔹 6. Set Comparisons
python
CopyEdit
a.issubset(b)
a.issuperset(b)
a.isdisjoint(b)
These return True or False.

🔹 7. Looping Through a Set


python
CopyEdit
for item in a:
print(item)

No indexing! Use a loop.

🔹 8. Frozen Sets (Immutable Sets)


python
CopyEdit
frozen = frozenset([1, 2, 3])

• You cannot modify a frozenset


• Useful for keys in dictionaries or constant sets

🔹 9. Use Cases of Sets

• Removing duplicates from a list:

python
CopyEdit
my_list = [1, 2, 2, 3]
no_duplicates = list(set(my_list))

• Fast membership testing:

python
CopyEdit
if 5 in my_set:
print("Found")

• Performing set-based math (union, intersection)

🧠 Practice Tasks:

1. Create a set of 5 numbers and add a new number to it.


2. Try adding a list to a set (observe the error).
3. Use set operations to find common and different elements in two sets.
4. Convert a list with duplicates into a set and back into a list.
5. Create a frozen set and try to modify it.

Let me know when you're done.


Tomorrow’s Topic: String Handling in Python — indexing, slicing, methods, formatting,
and best practices.

You said:
Continue

ChatGPT said:

Excellent! Now we’re moving into one of the most important and frequently used data types:

📘 Day 11: Strings in Python — Full Deep Dive

A string is a sequence of characters enclosed in single, double, or triple quotes.

python
CopyEdit
s1 = 'Hello'
s2 = "World"
s3 = '''Multi-line
string'''

Strings are immutable, indexable, iterable, and have many powerful methods.

🔹 1. String Indexing and Slicing

Just like lists and tuples:

python
CopyEdit
text = "Python"

print(text[0]) # P
print(text[-1]) # n

# Slicing
print(text[1:4]) # yth
print(text[:3]) # Pyt
print(text[3:]) # hon
print(text[::-1]) # Reverse: nohtyP
🔹 2. String Immutability

You can’t change part of a string directly:

python
CopyEdit
text = "Hello"
text[0] = "M" # Error: strings are immutable

Create a new one instead:

python
CopyEdit
text = "M" + text[1:]

🔹 3. Common String Methods


Method Description

lower() Converts to lowercase

upper() Converts to uppercase

title() Capitalizes each word

strip() Removes whitespace from both ends

replace(a, b) Replaces all a with b

split(sep) Splits string into a list

join(list) Joins list into string

startswith(sub) Checks if string starts with sub

endswith(sub) Checks if string ends with sub

find(sub) Finds first index of sub, else -1

count(sub) Counts how many times sub appears

🔹 4. String Formatting

Old-style (% formatting)
python
CopyEdit
name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age))

str.format() method
python
CopyEdit
print("Name: {}, Age: {}".format(name, age))
print("Name: {n}, Age: {a}".format(n=name, a=age))

f-Strings (recommended, Python 3.6+)


python
CopyEdit
print(f"Name: {name}, Age: {age}")

🔹 5. Escape Characters
Code Meaning

\n Newline

\t Tab

\\ Backslash

\' Single quote

\" Double quote

python
CopyEdit
print("Hello\nWorld")
print("He said: \"Python is cool\"")

🔹 6. Useful String Techniques

Reversing a string:
python
CopyEdit
s = "hello"
rev = s[::-1]

Checking if palindrome:
python
CopyEdit
s = "madam"
print(s == s[::-1]) # True

Count vowels:
python
CopyEdit
vowels = "aeiouAEIOU"
count = sum(1 for c in s if c in vowels)

🔹 7. Multiline Strings

Triple quotes can be used for documentation or storing multiple lines:

python
CopyEdit
text = """This is
a multi-line
string."""

🔹 8. String Membership Test


python
CopyEdit
"py" in "python" # True
"Java" not in "Python is fun" # True

🔹 9. String Comparisons

Strings can be compared using:

• == (equality)
• <, >, <=, >= (lexicographic order, like dictionary)

python
CopyEdit
print("apple" < "banana") # True

🔹 10. String Iteration


python
CopyEdit
for char in "Python":
print(char)
🧠 Practice Tasks:

1. Reverse the string "developer" using slicing.


2. Check if a user-entered string is a palindrome.
3. Count the number of vowels in "Information Security".
4. Ask the user for their name and print it using an f-string.
5. Split a sentence into words, then join them using hyphens.

Let me know when you finish these tasks.


Tomorrow’s Topic: Lists vs Tuples vs Sets vs Dictionaries — Comparison, use cases, and
decision-making guide.

You said:
Continue

ChatGPT said:

Awesome! Now that you’ve seen strings, lists, tuples, sets, and dictionaries individually, today’s
topic is about understanding how to choose between them.

📘 Day 12: Comparison of Lists, Tuples, Sets, and Dictionaries

Python offers multiple data structures — each with its own strengths and use cases.

1. Overview Table

Feature List Tuple Set Dictionary

Ordered Yes Yes No Yes (Python 3.7+)

Indexing Yes Yes No Yes (via keys)

Mutable Yes No Yes Yes

Duplicates Allowed Yes Yes No (in values only)

Keys/Values No No No Yes

Use Case General data Fixed data Math, uniqueness Lookup, structured data
2. When to Use Lists

Use when:

• You need to store a collection of ordered, changeable items.


• Duplicates are fine.
• You frequently need to add/remove items.

python
CopyEdit
tasks = ["todo", "read", "code"]
tasks.append("eat")

3. When to Use Tuples

Use when:

• Data should not be changed (immutability).


• Used as a key in a dictionary or element in a set.
• Lightweight, faster than lists.

python
CopyEdit
coordinates = (10, 20)

4. When to Use Sets

Use when:

• You need unique items only.


• You want to perform set operations: union, intersection, etc.
• Fast membership checking (x in set is fast).

python
CopyEdit
colors = {"red", "green", "blue"}
colors.add("yellow")

5. When to Use Dictionaries

Use when:
• You want to store data as key-value pairs.
• Quick lookups by a meaningful key.
• Each key maps to one value.

python
CopyEdit
student = {
"name": "Alice",
"marks": 90
}

6. Performance Comparison

Operation List Tuple Set Dictionary

Index access O(1) O(1) Not allowed O(1) via key

Membership check O(n) O(n) O(1) O(1)

Adding elements O(1) (amort.) Immutable O(1) O(1)

Mutability Mutable Immutable Mutable Mutable

7. Choosing the Right One — Real Use Cases

✅ Example 1: Student Info


python
CopyEdit
# Use dictionary
student = {"name": "Bob", "roll": 23, "marks": 82}
✅ Example 2: List of daily tasks
python
CopyEdit
tasks = ["read", "code", "sleep"]
✅ Example 3: Coordinates (fixed data)
python
CopyEdit
location = (12.5, 75.8)
✅ Example 4: Unique visitors to a website
python
CopyEdit
visitors = {"192.168.1.1", "192.168.1.2"}

8. Mutable vs Immutable Quick Check


Data Structure Mutable?

List Yes

Tuple No

Set Yes

Dictionary Yes

Practice Tasks

1. Create:
o a list of book titles
o a tuple for GPS coordinates
o a set of unique skills
o a dictionary for storing student name and marks
2. Try:
o Changing an element in a tuple (note the error).
o Adding duplicate items in a set (check result).
o Performing union and intersection of sets.
o Accessing dictionary values using keys.

Once you’ve practiced, we’ll move to:


Day 13: Functions in Python — parameters, return values, scope, recursion, and best
practices (in deep detail).

Would you like to continue now?

You said:
Continue

ChatGPT said:

Great! Now you're ready to dive into one of the most critical and powerful features in Python
— and in programming in general:

📘 Day 13: Functions in Python — Deep Explanation

A function is a reusable block of code that performs a specific task.


🔹 1. Why Use Functions?

Avoid repetition
Make code modular and clean
Easier to test and debug
Improve readability and reusability

🔹 2. Defining a Function
python
CopyEdit
def greet():
print("Hello!")

• def = keyword
• greet = function name
• () = parameters (optional)
• : = indicates start of function
body
• Indentation = Python uses indentation instead of {}

Calling the Function:


python
CopyEdit
greet() # Output: Hello!

🔹 3. Function with Parameters


python
CopyEdit
def greet(name):
print(f"Hello, {name}!")
python
CopyEdit
greet("Alice")
greet("Bob")

🔹 4. Function with Return Value


python
CopyEdit
def square(n):
return n * n
python
CopyEdit
result = square(5)
print(result) # 25

• return ends the function and sends data back.

🔹 5. Multiple Parameters
python
CopyEdit
def add(a, b):
return a + b
python
CopyEdit
print(add(3, 7)) # 10

🔹 6. Default Parameters
python
CopyEdit
def greet(name="Guest"):
print(f"Hello, {name}!")
python
CopyEdit
greet() # Hello, Guest!
greet("Ravi") # Hello, Ravi!

🔹 7. Keyword Arguments
python
CopyEdit
def intro(name, age):
print(f"{name} is {age} years old.")
python
CopyEdit
intro(age=30, name="Zara") # Order doesn't matter

🔹 8. Variable Number of Arguments

*args (Non-keyworded)
python
CopyEdit
def total(*numbers):
return sum(numbers)

print(total(1, 2, 3, 4)) # 10

**kwargs (Keyworded)
python
CopyEdit
def show_info(**info):
for key, value in info.items():
print(f"{key}: {value}")

show_info(name="Ali", age=21)

🔹 9. Scope of Variables

Local vs Global
python
CopyEdit
x = 5 # Global

def func():
x = 10 # Local
print(x)

func() # 10
print(x) # 5

global keyword
python
CopyEdit
x = 10

def modify():
global x
x = 20

modify()
print(x) # 20

🔹 10. Nested Functions


python
CopyEdit
def outer():
def inner():
print("Inner function")
inner()

outer()

🔹 11. Lambda (Anonymous Functions)

One-line function, often used as an argument.


python
CopyEdit
square = lambda x: x * x
print(square(5)) # 25

🔹 12. Recursion

A function calling itself:

python
CopyEdit
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
python
CopyEdit
print(factorial(5)) # 120

Always define a base case to avoid infinite recursion.

🔹 13. Docstrings (Documentation)


python
CopyEdit
def greet(name):
"""This function greets the user by name."""
print(f"Hello, {name}!")

Access with:

python
CopyEdit
print(greet.__doc__)

🧠 Practice Tasks

1. Write a function even_or_odd(n) that prints if a number is even or odd.


2. Write a function to compute the factorial of a number using recursion.
3. Write a function sum_all(*args) that returns the sum of any number of arguments.
4. Use **kwargs to print user profile data like name, age, country.
5. Create a lambda function to compute square, cube, and check if a number is even.
Let me know when you're ready.
Tomorrow’s Topic: Modules and Packages — importing, using built-ins, creating your
own, pip, and standard libraries.

You said:
Continue

ChatGPT said:

Great! Now that you understand functions well, let’s move on to the next fundamental topic:

📘 Day 14: Modules and Packages in Python — Deep Explanation

As your code grows, keeping everything in one file becomes messy. Python solves this using
modules and packages.

🔹 1. What is a Module?

A module is just a .py file containing functions, variables, or classes.

Example: your file math_utils.py


python
CopyEdit
# math_utils.py
def square(n):
return n * n

def cube(n):
return n * n * n

You can use this module in another file:

python
CopyEdit
# main.py
import math_utils

print(math_utils.square(4)) # 16
print(math_utils.cube(3)) # 27
🔹 2. Importing Modules
Syntax Meaning

import module Import full module

from module import x Import a specific function or variable

from module import * Import everything (not recommended)

import module as alias Use a short alias

Examples:
python
CopyEdit
import math
print(math.sqrt(16))

from math import sqrt


print(sqrt(16))

import math as m
print(m.pi)

🔹 3. Built-in Python Modules

Python includes many useful standard libraries.

Module Purpose

math Mathematical operations

random Random number generation

datetime Date and time handling

os File system operations

sys System-specific parameters

json JSON encoding and decoding

Examples:
python
CopyEdit
import random
print(random.randint(1, 10))

import datetime
print(datetime.datetime.now())

🔹 4. Creating Your Own Module

Create a Python file with functions, and save it in the same directory.

python
CopyEdit
# greetings.py
def say_hello(name):
return f"Hello, {name}"
python
CopyEdit
# main.py
import greetings
print(greetings.say_hello("Alice"))

🔹 5. What is a Package?

A package is a folder that contains multiple modules and a special file called __init__.py
(can be empty or used to initialize the package).

markdown
CopyEdit
mypackage/

├── __init__.py
├── module1.py
└── module2.py

Using the package:


python
CopyEdit
from mypackage import module1

Or:

python
CopyEdit
from mypackage.module2 import function_name

🔹 6. Installing External Packages with pip

pip is Python’s package manager. You can use it to install third-party libraries.
Example:
bash
CopyEdit
pip install requests

Then use it:

python
CopyEdit
import requests
response = requests.get("https://api.github.com")
print(response.status_code)

🔹 7. __name__ == "__main__" in Modules

This allows code to be run as a script or imported as a module.

python
CopyEdit
# calculator.py
def add(a, b):
return a + b

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

• When imported, __name__ != "__main__"


• When run directly, __name__ == "__main__"

🔹 8. Organizing Large Projects

Structure code like this:

css
CopyEdit
project/
├── main.py
├── utils/
│ ├── __init__.py
│ ├── file_utils.py
│ └── math_utils.py
└── data/

Now import like:

python
CopyEdit
from utils.math_utils import square

🧠 Practice Tasks

1. Create a module converter.py with functions:


o km_to_miles()
o celsius_to_fahrenheit()
2. Import and use them in main.py.
3. Use math, random, and datetime built-in modules in a program.
4. Create a small package with two modules:
o strings.py: with a function reverse_string()
o numbers.py: with a function is_even()

Once you practice this, we’ll move on to:

Day 15: File Handling in Python — Reading, Writing, Appending, Working with Text and
CSV Files

Let me know when you’re ready to continue!

You said:
Continue

ChatGPT said:

Excellent! Now that you understand modules and packages, let’s move forward to a crucial
topic for real-world programming:

📘 Day 15: File Handling in Python — Read, Write, Append, Text, and CSV Files

File handling allows you to work with external files — like text, logs, data files, etc.

🔹 1. Why File Handling?

Save data permanently (even after the program ends)


Read from configuration or data files
Write logs, reports, user data
Handle CSV, JSON, or other file formats
🔹 2. Opening a File — open()
python
CopyEdit
file = open("filename.txt", "mode")
Mode Meaning

'r' Read (default)

'w' Write (overwrites)

'a' Append

'x' Create new file

'b' Binary mode

't' Text mode (default)

🔹 3. Reading from a File

Suppose data.txt contains:

kotlin
CopyEdit
Hello world
Python is fun

Read entire file


python
CopyEdit
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

Read line by line


python
CopyEdit
file = open("data.txt", "r")
for line in file:
print(line.strip())
file.close()

readlines()
python
CopyEdit
lines = open("data.txt").readlines()
print(lines)

🔹 4. Writing to a File ('w')

• Overwrites file if it exists.


• Creates file if not.

python
CopyEdit
file = open("newfile.txt", "w")
file.write("This is a new file.\n")
file.write("Second line.")
file.close()

🔹 5. Appending to a File ('a')


python
CopyEdit
file = open("newfile.txt", "a")
file.write("\nAppended line.")
file.close()

🔹 6. Best Practice: with Block

Automatically closes the file.

python
CopyEdit
with open("data.txt", "r") as file:
content = file.read()
print(content)
python
CopyEdit
with open("log.txt", "a") as file:
file.write("Log entry\n")

🔹 7. File Methods
Method Description

.read(size) Read size characters

.readline() Read one line

.readlines() Read all lines into list


Method Description

.write(str) Write string to file

.seek(n) Move to byte n in file

.tell() Get current position

.close() Close the file

🔹 8. Working with CSV Files

Python has a built-in csv module.

Writing CSV:
python
CopyEdit
import csv

with open("students.csv", "w", newline="") as file:


writer = csv.writer(file)
writer.writerow(["Name", "Age", "Grade"])
writer.writerow(["Ali", 20, "A"])
writer.writerow(["Sara", 21, "B"])

Reading CSV:
python
CopyEdit
import csv

with open("students.csv", "r") as file:


reader = csv.reader(file)
for row in reader:
print(row)

🔹 9. Handling File Not Found / Errors


python
CopyEdit
try:
with open("missing.txt") as file:
data = file.read()
except FileNotFoundError:
print("File not found!")

You can also use except IOError, PermissionError, etc.


🔹 10. Practical Use Cases

• Logging user actions


• Reading configuration files
• Exporting data to reports
• Importing data from CSV

🧠 Practice Tasks

1. Create a text file, write 5 lines using 'w', and print them using 'r'.
2. Append 2 more lines using 'a'.
3. Write a program that takes user input and stores it in a file.
4. Create a CSV file of books: Title, Author, Year.
5. Read the CSV and display each row formatted nicely.

Once you complete these, we’ll move to:

Day 16: Object-Oriented Programming (OOP) in Python — Classes, Objects, Inheritance,


Encapsulation, and more

Let me know when you’re ready to continue!

You said:
Continue

ChatGPT said:

Excellent! Today, we’ll start one of the most powerful features in programming — especially
useful in real-world projects and large-scale systems:

📘 Day 16: Object-Oriented Programming (OOP) in Python — Deep Explanation

OOP is a way of organizing code using classes and objects to model real-world things.
🔹 1. What is OOP?

OOP stands for Object-Oriented Programming — a paradigm based on the concept of


“objects”, which contain:

• Attributes (data)
• Methods (functions)

🔹 2. Basic Concepts in OOP


Concept Meaning

Class Blueprint for creating objects

Object Instance of a class

Method Function inside a class

Constructor Special method __init__() to initialize object

self Refers to the current object (like this in C++/Java)

Encapsulation Keeping data private and safe

Inheritance Child class inherits features from parent class

Polymorphism Same method name behaves differently depending on the context

🔹 3. Defining a Class and Creating Objects


python
CopyEdit
class Person:
def __init__(self, name, age): # Constructor
self.name = name
self.age = age

def greet(self): # Method


print(f"Hi, my name is {self.name} and I'm {self.age} years old.")

# Creating objects
p1 = Person("Alice", 25)
p2 = Person("Bob", 30)

p1.greet()
p2.greet()
🔹 4. Understanding __init__() and self

• __init__() is automatically called when an object is created.


• self allows you to access variables and methods inside the object.

🔹 5. Class Attributes vs Instance Attributes


python
CopyEdit
class Dog:
species = "Canine" # Class attribute

def __init__(self, name):


self.name = name # Instance attribute
python
CopyEdit
d = Dog("Tommy")
print(d.name) # Tommy
print(d.species) # Canine

🔹 6. Encapsulation and Access Control

Python uses naming conventions:

Notation Meaning

public_var Public (default)

_protected Protected (by convention)

__private Private (name mangled)

python
CopyEdit
class Student:
def __init__(self, name):
self.__name = name # Private variable

def get_name(self):
return self.__name

def set_name(self, new_name):


self.__name = new_name

🔹 7. Inheritance

Inheritance lets a class (child) use properties and methods from another class (parent).
python
CopyEdit
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def speak(self):
print("Dog barks")

a = Animal()
d = Dog()

a.speak() # Animal speaks


d.speak() # Dog barks (overrides parent)

🔹 8. super() Function

Use super() to access the parent class.

python
CopyEdit
class Parent:
def __init__(self):
print("Parent constructor")

class Child(Parent):
def __init__(self):
super().__init__()
print("Child constructor")

c = Child()

🔹 9. Polymorphism

Same function name can behave differently in different classes.

python
CopyEdit
class Cat:
def sound(self):
print("Meow")

class Dog:
def sound(self):
print("Bark")

def animal_sound(animal):
animal.sound()

c = Cat()
d = Dog()
animal_sound(c)
animal_sound(d)

🔹 10. Dunder (Magic) Methods

Python classes can define special methods like:

Method Purpose

__init__ Constructor

__str__ String representation

__len__ Used by len()

__add__ Used by + operator

__eq__ Equality check

python
CopyEdit
class Book:
def __init__(self, title):
self.title = title

def __str__(self):
return f"Book: {self.title}"

b = Book("Python 101")
print(b) # Book: Python 101

🧠 Practice Tasks

1. Create a Car class with attributes: brand, model, year.


2. Add a method start_engine().
3. Create a child class ElectricCar that inherits from Car and overrides start_engine().
4. Create a BankAccount class with private balance and methods for deposit/withdraw.
5. Use __str__() to print a meaningful message for any class object.

Once you're done with this, we’ll go to:

Day 17: Exception Handling — Try, Except, Else, Finally, Custom Errors

Let me know when you're ready to continue!


You said:
Continue

ChatGPT said:

Awesome! Let’s dive into the next essential topic that every robust Python program needs:

📘 Day 17: Exception Handling in Python — Deep Explanation

Errors happen — in user input, files, networks, etc. Exception handling helps you gracefully
handle errors without crashing your program.

🔹 1. What are Exceptions?

Exceptions are runtime errors that interrupt normal flow.

Common examples:

• ZeroDivisionError
• FileNotFoundError
• ValueError
• TypeError

🔹 2. Basic Try-Except Block


python
CopyEdit
try:
x = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")

• Code in try runs first.


• If exception happens, code in matching except runs.
• Program continues after except block.

🔹 3. Handling Multiple Exceptions


python
CopyEdit
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Division by zero is not allowed.")
except ValueError:
print("Invalid input, enter an integer.")

🔹 4. else Clause

Runs if no exceptions occur.

python
CopyEdit
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print(f"You entered {num}")

🔹 5. finally Clause

Runs always, no matter what.

python
CopyEdit
try:
file = open("data.txt")
except FileNotFoundError:
print("File not found!")
else:
print(file.read())
finally:
print("Executing cleanup...")
file.close()

🔹 6. Raising Exceptions

You can raise exceptions yourself with raise.

python
CopyEdit
def check_age(age):
if age < 18:
raise ValueError("Must be 18 or older.")
print("Access granted.")

try:
check_age(16)
except ValueError as e:
print(e)
🔹 7. Custom Exceptions

Create your own exception by inheriting from Exception.

python
CopyEdit
class CustomError(Exception):
pass

def test(value):
if value < 0:
raise CustomError("Negative value not allowed.")

try:
test(-5)
except CustomError as e:
print(e)

🔹 8. Exception Object and Traceback

Capture the exception object to get error details:

python
CopyEdit
try:
10 / 0
except ZeroDivisionError as e:
print(f"Error occurred: {e}")

🔹 9. Using assert Statement

Used to check conditions during development.

python
CopyEdit
x = 5
assert x > 0, "x must be positive"

If the condition fails, it raises an AssertionError.

🔹 10. Good Practices

• Handle specific exceptions instead of a general except:.


• Avoid silent failures.
• Always clean resources (files, network) in finally.
• Use meaningful messages in exceptions.

🧠 Practice Tasks

1. Write a program that reads a number from the user and divides 100 by that number with
proper exception handling.
2. Open a file safely and handle the error if the file is missing.
3. Raise an exception if a user enters an invalid password (length < 8).
4. Create a custom exception for invalid email format.
5. Use assert to validate function inputs.

After mastering exception handling, you’ll be ready for:

Day 18: Working with Libraries — Using requests for HTTP, JSON Handling

Tell me when you want to continue!

You said:
Continue

ChatGPT said:

Great! Now let's dive into working with external data and the internet — a vital skill in modern
programming:

📘 Day 18: Working with Libraries — HTTP Requests & JSON Handling in Python

1. What is requests?

• requests is a powerful Python library to send HTTP requests easily.


• Used to interact with web APIs, download web pages, post data, etc.

2. Installing requests

If you don’t have it yet:


bash
CopyEdit
pip install requests

3. Basic GET Request


python
CopyEdit
import requests

response = requests.get("https://api.github.com")
print(response.status_code) # 200 means success
print(response.headers['Content-Type'])
print(response.text) # Raw response content (usually JSON or
HTML)

4. GET Request with Parameters


python
CopyEdit
params = {'q': 'python', 'sort': 'stars'}
response = requests.get("https://api.github.com/search/repositories",
params=params)
print(response.json()) # Parse JSON response

5. POST Request

Sending data to the server:

python
CopyEdit
data = {'username': 'alice', 'password': '1234'}
response = requests.post("https://httpbin.org/post", data=data)
print(response.json())

6. Handling JSON

JSON (JavaScript Object Notation) is a common data format for APIs.

• response.json() converts JSON string into Python dictionaries/lists.


• You can also convert Python data to JSON string using json module.

python
CopyEdit
import json
data = {'name': 'Bob', 'age': 25}
json_str = json.dumps(data) # Python dict -> JSON string
print(json_str)

parsed_data = json.loads(json_str) # JSON string -> Python dict


print(parsed_data['name'])

7. Headers and Authentication

Set HTTP headers like User-Agent or Authentication tokens:

python
CopyEdit
headers = {'User-Agent': 'MyApp/1.0'}

response = requests.get("https://api.github.com/user", headers=headers,


auth=('user', 'pass'))

8. Timeouts & Error Handling


python
CopyEdit
try:
response = requests.get("https://example.com", timeout=5)
response.raise_for_status() # Raises HTTPError for bad responses
except requests.exceptions.RequestException as e:
print("Request failed:", e)

9. Practical Example: Get GitHub User Info


python
CopyEdit
import requests

username = input("Enter GitHub username: ")


url = f"https://api.github.com/users/{username}"
response = requests.get(url)

if response.status_code == 200:
data = response.json()
print(f"Name: {data['name']}")
print(f"Public repos: {data['public_repos']}")
else:
print("User not found.")
🧠 Practice Tasks

1. Use requests to get weather data from a public API (e.g., OpenWeatherMap).
2. Post JSON data to httpbin.org and print the response.
3. Parse JSON from an API and extract specific information.
4. Handle possible request errors and timeouts.
5. Create a program that asks for a GitHub username and prints the user's bio and repo
count.

Ready for Day 19: Working with Databases — SQLite3 in Python whenever you say!

You said:
Continue

ChatGPT said:

Awesome! Now let’s get into managing data storage locally with databases — super important
for almost any real app.

📘 Day 19: Working with Databases — SQLite3 in Python

1. What is SQLite?

• Lightweight, serverless, file-based SQL database.


• Perfect for small to medium projects.
• Comes built-in with Python (sqlite3 module).

2. Connecting to a Database
python
CopyEdit
import sqlite3

conn = sqlite3.connect('mydatabase.db') # Connect/create database file


cursor = conn.cursor() # Create cursor to execute SQL
commands

3. Creating a Table
python
CopyEdit
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')
conn.commit()

4. Inserting Data
python
CopyEdit
cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice', 30))
conn.commit()

Using ? placeholders prevents SQL injection (safe queries).

5. Querying Data
python
CopyEdit
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
for row in rows:
print(row)

6. Updating Data
python
CopyEdit
cursor.execute('UPDATE users SET age = ? WHERE name = ?', (31, 'Alice'))
conn.commit()

7. Deleting Data
python
CopyEdit
cursor.execute('DELETE FROM users WHERE name = ?', ('Alice',))
conn.commit()

8. Closing the Connection


Always close to free resources.

python
CopyEdit
conn.close()

9. Using with Statement for Safety


python
CopyEdit
with sqlite3.connect('mydatabase.db') as conn:
cursor = conn.cursor()
# Your queries here

10. Putting It All Together


python
CopyEdit
import sqlite3

def create_user(name, age):


with sqlite3.connect('mydatabase.db') as conn:
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY
KEY, name TEXT, age INTEGER)')
cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', (name,
age))
conn.commit()

def get_users():
with sqlite3.connect('mydatabase.db') as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM users')
return cursor.fetchall()

create_user('Bob', 24)
users = get_users()
print(users)

🧠 Practice Tasks

1. Create a products table with fields: id, name, price.


2. Insert 3 products.
3. Write a function to update the price of a product.
4. Write a function to delete a product by name.
5. Fetch and display all products sorted by price.
Let me know when you want to move on to Day 20: Advanced Python Topics —
Decorators and Generators!

You said:
Continue

ChatGPT said:

Perfect! Let’s get into some of Python’s most elegant and powerful features: Decorators and
Generators.

📘 Day 20: Advanced Python Topics — Decorators & Generators

1. Generators

What are Generators?

• Special functions that return an iterator.


• They yield values one at a time, saving memory.
• Useful for large data or streams.

How are Generators Different from Regular Functions?

• Regular functions use return once and exit.


• Generators use yield to produce values one by one, pausing between yields.

Example:
python
CopyEdit
def count_up_to(max):
count = 1
while count <= max:
yield count # Pause here and return count
count += 1

counter = count_up_to(5)
print(next(counter)) # 1
print(next(counter)) # 2
print(next(counter)) # 3

• Using for loop:

python
CopyEdit
for num in count_up_to(3):
print(num)
2. Why Use Generators?

• Efficient memory usage.


• Can represent infinite sequences.
• Lazily evaluated — values generated on demand.

3. Generator Expressions

Like list comprehensions but with () instead of [].

python
CopyEdit
gen = (x * x for x in range(5))
print(next(gen)) # 0
print(next(gen)) # 1

4. Decorators

What are Decorators?

• Functions that modify behavior of other functions.


• Used to add functionality without changing original function code.
• Common in logging, access control, timing, etc.

5. Basic Decorator Syntax


python
CopyEdit
def decorator_func(original_func):
def wrapper_func():
print("Before the function runs.")
original_func()
print("After the function runs.")
return wrapper_func

@decorator_func
def say_hello():
print("Hello!")

say_hello()
Output:

pgsql
CopyEdit
Before the function runs.
Hello!
After the function runs.

6. How Decorators Work

• @decorator_func is syntactic sugar for:

python
CopyEdit
say_hello = decorator_func(say_hello)

• The decorator returns a wrapper function which adds behavior.

7. Decorators with Arguments


python
CopyEdit
def decorator_func(original_func):
def wrapper_func(*args, **kwargs):
print("Before")
result = original_func(*args, **kwargs)
print("After")
return result
return wrapper_func

@decorator_func
def greet(name):
print(f"Hello, {name}")

greet("Alice")

8. Practical Decorator Example — Timing


python
CopyEdit
import time

def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.4f} seconds.")
return result
return wrapper

@timer
def waste_time(num):
for _ in range(num):
sum([i**2 for i in range(10000)])

waste_time(5)

9. Fun Fact: Multiple Decorators

You can stack decorators:

python
CopyEdit
@decorator1
@decorator2
def func():
pass

Equivalent to:

python
CopyEdit
func = decorator1(decorator2(func))

10. Summary

Topic Key Point

Generators Use yield, save memory, produce sequences

Generator Expr Compact syntax for generators

Decorators Wrap functions to modify/extend behavior

Wrapper Func Inner function in decorator that runs original

🧠 Practice Tasks

1. Write a generator that yields Fibonacci numbers up to n.


2. Create a decorator that logs the arguments and return value of a function.
3. Write a generator expression to produce squares of numbers 1 to 10.
4. Create a decorator to check if arguments to a function are positive integers.
5. Combine two decorators on a sample function.

Let me know when you want to keep going with Day 21: File Handling and Context
Managers in Python!

You said:
Continue

ChatGPT said:

Awesome! Let’s move forward to an essential topic that you’ll use constantly: File Handling
and Context Managers in Python.

📘 Day 21: File Handling and Context Managers

1. Opening and Closing Files

Use the open() function:

python
CopyEdit
file = open('example.txt', 'r') # 'r' = read mode
content = file.read()
print(content)
file.close() # Always close the file!

2. File Modes

Mode Meaning

'r' Read (default)

'w' Write (creates or truncates)

'a' Append

'b' Binary mode (use with other modes)

'x' Create new file, fail if exists


3. Reading Files

• Read whole file: file.read()


• Read line by line:

python
CopyEdit
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # strip removes newline chars

• Read specific number of characters: file.read(10)

4. Writing Files
python
CopyEdit
with open('output.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("Writing to a file.")

5. Appending to Files
python
CopyEdit
with open('output.txt', 'a') as file:
file.write("\nAppending this line.")

6. Context Managers (with Statement)

• Automatically handles opening and closing files.


• Safer and cleaner.

Example:

python
CopyEdit
with open('example.txt', 'r') as file:
content = file.read()
print("File closed automatically after this block.")

7. Binary Files
Use 'rb' or 'wb' modes for images, audio, etc.

8. Handling Exceptions in File I/O


python
CopyEdit
try:
with open('missing.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File does not exist!")

9. Working with JSON Files

Save and load JSON data easily.

python
CopyEdit
import json

data = {'name': 'Alice', 'age': 30}

# Write JSON
with open('data.json', 'w') as f:
json.dump(data, f)

# Read JSON
with open('data.json', 'r') as f:
loaded_data = json.load(f)
print(loaded_data)

10. Custom Context Managers

You can create your own context manager using __enter__ and __exit__ methods or using
contextlib.

python
CopyEdit
from contextlib import contextmanager

@contextmanager
def open_file(name, mode):
f = open(name, mode)
try:
yield f
finally:
f.close()
with open_file('example.txt', 'r') as f:
content = f.read()

🧠 Practice Tasks

1. Write a program to read a file and count the number of words.


2. Write a program to write a list of strings into a file, each on a new line.
3. Append new data to an existing file.
4. Handle the exception when reading a non-existent file.
5. Save a dictionary to a JSON file and read it back.

Tell me when you want to go next with Day 22: Object-Oriented Programming (OOP) in
Python!

You said:
Continue

ChatGPT said:

Great! Now we’re moving into a core programming paradigm: Object-Oriented Programming
(OOP) in Python — a powerful way to organize your code using objects.

📘 Day 22: Object-Oriented Programming (OOP) in Python — Deep Dive

1. What is OOP?

OOP organizes code around objects rather than just functions and logic.
An object represents real-world entities with attributes (data) and methods (functions).

2. Class and Object

• Class: blueprint/template for creating objects.


• Object (Instance): actual entity created from class.

python
CopyEdit
class Dog:
def __init__(self, name, age):
self.name = name # attribute
self.age = age

def bark(self): # method


print(f"{self.name} says Woof!")

dog1 = Dog("Buddy", 3)
dog1.bark() # Buddy says Woof!

3. The __init__ Method

• Called automatically when an object is created.


• Initializes the object's attributes.
• self refers to the current instance.

4. Instance Variables vs Class Variables


python
CopyEdit
class Cat:
species = "Felis catus" # class variable shared by all

def __init__(self, name, age):


self.name = name # instance variable unique to object
self.age = age

cat1 = Cat("Whiskers", 2)
cat2 = Cat("Tom", 4)
print(cat1.species) # Felis catus
print(cat2.species) # Felis catus

5. Methods

• Instance methods (with self): operate on object’s data.


• Class methods (with @classmethod): operate on the class itself.
• Static methods (with @staticmethod): utility functions inside class.

6. Class Method Example


python
CopyEdit
class Person:
count = 0
def __init__(self, name):
self.name = name
Person.count += 1

@classmethod
def total_people(cls):
return cls.count

p1 = Person("Alice")
p2 = Person("Bob")
print(Person.total_people()) # 2

7. Static Method Example


python
CopyEdit
class Math:
@staticmethod
def add(x, y):
return x + y

print(Math.add(5, 7)) # 12

8. Inheritance

• Allows one class to inherit attributes and methods from another.


• Supports code reuse and polymorphism.

python
CopyEdit
class Animal:
def speak(self):
print("Animal sound")

class Dog(Animal):
def speak(self):
print("Woof!")

dog = Dog()
dog.speak() # Woof!

9. Encapsulation

• Control access to class data.


• Use single _ (protected) or double __ (private) underscores.

python
CopyEdit
class Account:
def __init__(self, balance):
self.__balance = balance # private attribute

def get_balance(self):
return self.__balance

acc = Account(1000)
print(acc.get_balance()) # 1000
# print(acc.__balance) # AttributeError

10. Polymorphism

• Same method name, different behaviors depending on the object.

python
CopyEdit
class Cat(Animal):
def speak(self):
print("Meow")

def animal_speak(animal):
animal.speak()

animal_speak(Dog()) # Woof!
animal_speak(Cat()) # Meow

🧠 Practice Tasks

1. Create a Car class with attributes and methods for acceleration and braking.
2. Implement inheritance: ElectricCar inherits from Car and adds battery capacity.
3. Create a class method to keep track of how many cars were created.
4. Use private attributes to store fuel level.
5. Write polymorphic method for different types of vehicles (Car, Truck, Bike).

Let me know when you want to continue with Day 23: Modules and Packages in Python!

You said:
Continue

ChatGPT said:

Awesome, let’s dive into organizing your Python code effectively using Modules and Packages
— essential for scaling your projects!
📘 Day 23: Modules and Packages in Python

1. What is a Module?

• A module is a file containing Python code (functions, classes, variables).


• Helps organize code logically.
• Use modules to reuse code across projects.

Example: math.py is a module (or Python’s built-in math module).

2. Creating and Using Your Own Module

Create a file named mymath.py:

python
CopyEdit
def add(x, y):
return x + y

def subtract(x, y):


return x - y

Now, in another file or Python shell:

python
CopyEdit
import mymath

print(mymath.add(5, 3)) # 8
print(mymath.subtract(5, 3)) # 2

3. Import Variations

• Import specific functions/classes:

python
CopyEdit
from mymath import add
print(add(10, 4))

• Import with alias:


python
CopyEdit
import mymath as mm
print(mm.subtract(10, 4))

• Import all (not recommended):

python
CopyEdit
from mymath import *

4. What is a Package?

• A package is a folder/directory containing multiple modules.


• Must contain an __init__.py file (can be empty).
• Allows hierarchical module structure.

Example directory structure:

markdown
CopyEdit
my_package/
__init__.py
math_ops.py
string_ops.py

5. Using Packages

In math_ops.py:

python
CopyEdit
def multiply(x, y):
return x * y

In string_ops.py:

python
CopyEdit
def to_upper(s):
return s.upper()

Import from package:

python
CopyEdit
from my_package import math_ops, string_ops
print(math_ops.multiply(4, 5)) # 20
print(string_ops.to_upper('hello')) # HELLO

6. Relative Imports

Inside a package module, you can use relative imports:

python
CopyEdit
from .math_ops import multiply # imports from same package

7. The __init__.py file

• Marks the directory as a package.


• Can be used to initialize package or expose select modules/functions.

Example:

python
CopyEdit
from .math_ops import multiply
from .string_ops import to_upper

Now, importing the package:

python
CopyEdit
from my_package import multiply, to_upper

8. Python Standard Library Modules

• Python comes with many built-in modules like os, sys, random, datetime.
• Use them to avoid reinventing the wheel.

Example:

python
CopyEdit
import os

print(os.getcwd()) # Current working directory

9. Installing Third-Party Packages


• Use pip to install external packages.

bash
CopyEdit
pip install requests

Use in code:

python
CopyEdit
import requests

response = requests.get('https://api.github.com')
print(response.status_code)

10. Creating a Package for Distribution

• Structure your code properly.


• Add setup.py file.
• Use tools like setuptools or poetry.

🧠 Practice Tasks

1. Create a module with at least 3 math-related functions.


2. Create a package folder with two modules: one for math, one for strings.
3. Write an __init__.py that exposes selected functions from both modules.
4. Use Python’s random module to generate a random number.
5. Install and import a third-party package like requests or numpy.

Let me know when you want to move to Day 24: Error Handling and Exceptions in
Python!

You said:
Continue

ChatGPT said:

Alright! Let’s get into a crucial topic that keeps your programs robust: Error Handling and
Exceptions in Python — handled gracefully, they make your code professional and bug-
resistant.
📘 Day 24: Error Handling and Exceptions

1. What are Exceptions?

• Exceptions are runtime errors that disrupt normal flow.


• Python raises exceptions when things go wrong (e.g., division by zero, file not found).

2. Basic Try-Except Block


python
CopyEdit
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")

• try: code that might cause an exception.


• except: code that handles the exception.

3. Catching Multiple Exceptions


python
CopyEdit
try:
x = int(input("Enter a number: "))
result = 10 / x
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("You cannot divide by zero.")

4. Catching All Exceptions


python
CopyEdit
try:
# risky code
except Exception as e:
print(f"Error occurred: {e}")

Note: Catching all exceptions is useful but can hide bugs if overused.
5. The else Clause

Runs if no exception occurs.

python
CopyEdit
try:
x = int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print(f"You entered {x}.")

6. The finally Clause

Always runs, whether exception occurred or not — useful for cleanup.

python
CopyEdit
try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
print("File closed.")

7. Raising Exceptions

You can raise exceptions manually.

python
CopyEdit
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
print(f"Age is {age}")

check_age(-1)

8. Custom Exception Classes

Create your own exception type by subclassing Exception.


python
CopyEdit
class MyError(Exception):
pass

def do_something(value):
if value < 0:
raise MyError("Value cannot be negative")

try:
do_something(-5)
except MyError as e:
print(f"Caught custom error: {e}")

9. Best Practices

• Catch specific exceptions.


• Use finally for cleanup.
• Avoid silent failures — always handle or log exceptions.
• Raise exceptions with meaningful messages.

10. Exception Hierarchy

• Exceptions inherit from the base class BaseException.


• Common built-in exceptions: ValueError, TypeError, IOError, IndexError,
KeyError.

🧠 Practice Tasks

1. Write a function that divides two numbers and handles division by zero.
2. Implement user input handling with try-except for invalid inputs.
3. Write a function that raises an exception for invalid arguments.
4. Create and use a custom exception for a simple validation.
5. Practice using finally to close files or release resources.

Ready to move on to Day 25: Working with Libraries and Virtual Environments?

You said:
Continue
ChatGPT said:

Great! Now let's explore how to effectively use libraries and manage your Python environment
using virtual environments. This is essential for working on real projects and keeping
dependencies clean and organized.

📘 Day 25: Working with Libraries and Virtual Environments

1. What are Libraries (Packages)?

• Libraries are collections of pre-written code (modules) that you can use to add
functionality to your programs.
• Examples: requests for HTTP, numpy for math, pandas for data analysis.

2. Installing Libraries with pip

• pip is Python’s package manager.


• Install a library:

bash
CopyEdit
pip install requests

• Upgrade a library:

bash
CopyEdit
pip install --upgrade requests

• Uninstall a library:

bash
CopyEdit
pip uninstall requests

3. Using Installed Libraries

Example with requests:

python
CopyEdit
import requests

response = requests.get('https://api.github.com')
print(response.status_code)
print(response.json())

4. What is a Virtual Environment?

• A virtual environment is an isolated workspace for Python projects.


• Keeps project dependencies separate, avoiding version conflicts.
• Helps maintain reproducible environments.

5. Creating a Virtual Environment

In your project folder, run:

bash
CopyEdit
python -m venv venv

• This creates a folder named venv with isolated Python environment.

6. Activating the Virtual Environment

• On Windows:

bash
CopyEdit
venv\Scripts\activate

• On macOS/Linux:

bash
CopyEdit
source venv/bin/activate

You’ll see (venv) prefix in your terminal indicating it's active.

7. Installing Libraries in Virtual Environment


Once activated, use pip as usual. Libraries installed here won’t affect global Python installation.

8. Deactivating the Virtual Environment

Simply run:

bash
CopyEdit
deactivate

9. Freezing and Sharing Dependencies

• To save current installed packages:

bash
CopyEdit
pip freeze > requirements.txt

• To install from requirements.txt:

bash
CopyEdit
pip install -r requirements.txt

10. Using requirements.txt

It helps other developers replicate your environment exactly.

🧠 Practice Tasks

1. Create a virtual environment in a project folder.


2. Activate it and install the requests library.
3. Write a simple script that fetches data from an API using requests.
4. Freeze installed packages to requirements.txt.
5. Deactivate the environment, then recreate it using the requirements.txt.

When you're ready, we can continue with Day 26: Advanced Data Structures in Python
(Sets, Tuples, Dictionaries in detail)!
You said:
Continue

ChatGPT said:

Sure! Let’s get deeper into Python’s essential advanced data structures: Sets, Tuples, and
Dictionaries — their characteristics, usage, and powerful methods.

📘 Day 26: Advanced Data Structures in Python — Sets, Tuples, Dictionaries

1. Tuples

• Immutable ordered sequences of elements.


• Defined with parentheses () or just commas.
• Once created, cannot be changed (no add/remove).

python
CopyEdit
t = (1, 2, 3)
print(t[0]) # 1

# Can also create without parentheses


t2 = 4, 5, 6

Why use tuples?

• Fixed data.
• Faster than lists.
• Can be used as dictionary keys (immutable).

Tuple Methods (limited)

• count(): number of occurrences


• index(): first index of value

Example:

python
CopyEdit
t = (1, 2, 3, 2)
print(t.count(2)) # 2
print(t.index(3)) # 2
2. Sets

• Unordered collections of unique elements.


• Defined with curly braces {} or set() constructor.
• Used for membership testing, removing duplicates, set operations.

python
CopyEdit
s = {1, 2, 3, 3, 4}
print(s) # {1, 2, 3, 4}

Set Operations

• Union (| or .union()): all unique elements

python
CopyEdit
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}

• Intersection (& or .intersection()): common elements

python
CopyEdit
print(a & b) # {3}

• Difference (- or .difference()): elements in a but not in b

python
CopyEdit
print(a - b) # {1, 2}

• Symmetric Difference (^): elements in either but not both

python
CopyEdit
print(a ^ b) # {1, 2, 4, 5}

Set Methods

• add(elem): add element


• remove(elem): remove element, raises error if not found
• discard(elem): remove element if present, no error if not found
• pop(): remove and return an arbitrary element
• clear(): remove all elements
3. Dictionaries

• Unordered key-value pairs.


• Keys must be immutable types (strings, numbers, tuples).
• Values can be any type.
• Defined with {} or dict().

python
CopyEdit
d = {'name': 'Alice', 'age': 25}
print(d['name']) # Alice

Dictionary Methods and Operations

• Add or update:

python
CopyEdit
d['age'] = 26
d['city'] = 'New York'

• Remove:

python
CopyEdit
del d['city']

• Common methods:

Method Description

keys() Returns all keys

values() Returns all values

items() Returns key-value pairs

get(key, def) Returns value for key or default if key missing

pop(key) Removes and returns value by key

clear() Clears all items


Example: Iterating Over a Dictionary
python
CopyEdit
for key, value in d.items():
print(f"{key}: {value}")

4. Dictionary Comprehension

Create dicts concisely:

python
CopyEdit
squares = {x: x*x for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

5. When to Use Which?

Data Unique
Ordered? Mutable? Use Case
Structure Elements?

Tuple Yes No No Fixed collection, keys in dict

Unique items, membership,


Set No Yes Yes
math ops

No (3.7+ insertion order


Dictionary Yes Keys unique Key-value mappings, lookups
preserved)

🧠 Practice Tasks

1. Create a tuple and try accessing/modifying elements.


2. Create sets and perform union, intersection, difference.
3. Build a dictionary of your favorite books with author names.
4. Iterate through dictionary and print keys and values.
5. Use dictionary comprehension to create a mapping of numbers to their cubes.

Ready for Day 27: File Operations Deep Dive and Working with CSV/JSON files?

You might also like