python
python
🔹 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.
• Install Python
• Set up a code editor
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”
Choose one:
• VS Code: https://code.visualstudio.com
• Thonny (Beginner-friendly): https://thonny.org
After installation, open the Python shell or your editor and type:
python
CopyEdit
print("Hello, Python!")
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:
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:
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:
🔹 Type Checking
python
CopyEdit
name = "Alice"
print(type(name)) # Output: <class 'str'>
age = 25
print(type(age)) # Output: <class 'int'>
# Check types
print(type(first_name))
print(type(age))
print(type(height))
print(type(is_student))
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.
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).
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
Operator Description Example Output
* Multiplication 10 * 5 50
// Floor Division 10 // 3 3
% Modulus 10 % 3 1
** Exponent (power) 2 ** 3 8
🔹 2. Assignment Operators
Operator Meaning Example Same as
= Assign value x = 5 —
-= Subtract x -= 2 x = x - 2
*= Multiply x *= 2 x = x * 2
/= Divide x /= 2 x = x / 2
%= Modulo x %= 2 x = x % 2
== Equal to 5 == 5 True
🔹 4. Logical Operators
Python uses plain English words instead of symbols (&&, ||, !) like in C/C++.
🔹 5. Identity Operators
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
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")
You said:
Explain deeply conditionals
ChatGPT said:
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.
• if
• elif (short for "else if")
• else
🔸 1. Basic if Statement
python
CopyEdit
age = 18
Syntax Breakdown:
🔸 2. if with else
python
CopyEdit
age = 16
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
🔸 4. Nested Conditionals
python
CopyEdit
age = 20
citizen = True
if age >= 18:
if citizen:
print("Eligible to vote")
else:
print("Not a citizen")
else:
print("Underage")
One-line if:
python
CopyEdit
a = 10
if a > 5: print("a is greater than 5")
python
CopyEdit
age = 20
has_id = True
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): "))
You said:
Loops
ChatGPT said:
Loops let you repeat a block of code multiple times. Python supports two main types of loops:
• for loop
• while loop
Output:
CopyEdit
0
1
2
3
4
python
CopyEdit
for i in range(1, 10, 2):
print(i)
Output:
CopyEdit
1
3
5
7
9
python
CopyEdit
count = 0
Output:
CopyEdit
0
1
2
3
4
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
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")
for syntax Uses 3-part loop (init; cond; inc) Iterates over sequences
🧠 Practice Tasks:
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++.
🔹 What is a Function?
• To organize code
• To avoid repetition
• To increase modularity
• To make debugging easier
🔸 1. Defining a Function
python
CopyEdit
def greet():
print("Hello!")
🔸 2. Calling a Function
python
CopyEdit
greet()
Output:
CopyEdit
Hello!
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
🔸 5. Default Parameters
python
CopyEdit
def greet(name="Guest"):
print("Hello", name)
This avoids function overloading (like in C++). Instead of writing multiple versions, just use
default values.
show(name="Alice", age=25)
Output:
yaml
CopyEdit
name : Alice
age : 25
s, p = stats(3, 4)
print("Sum:", s, "Product:", p)
🔸 9. Scope of Variables
Scope Type Description
func()
print(x) # Error: x not defined outside
def show():
print(x)
show() # 5
def change():
global x
x = 10
change()
print(x) # 10
python
CopyEdit
square = lambda x: x * x
print(square(5)) # 25
Equivalent to:
python
CopyEdit
def square(x):
return x * x
python
CopyEdit
# Function
def greet():
print("Hello")
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:
You said:
Continue
ChatGPT said:
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"]
• Strings
• Numbers
• Other lists
• Mixed types
python
CopyEdit
my_list = [1, "hello", 3.14, [10, 20]]
🔹 2. Accessing Elements
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]
🔹 4. Modifying Elements
python
CopyEdit
fruits[1] = "orange"
print(fruits) # ['apple', 'orange', 'cherry']
Examples:
python
CopyEdit
fruits = ["banana", "apple", "cherry"]
fruits.append("orange")
fruits.sort()
fruits.remove("banana")
print(fruits)
Output:
css
CopyEdit
['apple', 'cherry', 'orange']
Using index:
python
CopyEdit
for i in range(len(fruits)):
print(i, fruits[i])
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
print(matrix[0][1]) # 2
🧠 Practice Tasks:
You said:
Continue
ChatGPT said:
Tuples are very similar to lists, but they are immutable (they can’t be changed once created).
This makes them:
🔹 1. What is a Tuple?
python
CopyEdit
my_tuple = (10, 20, 30)
python
CopyEdit
t = 1, 2, 3
python
CopyEdit
t = (5)
print(type(t)) # ➤ int
Correct:
python
CopyEdit
t = (5,)
print(type(t)) # ➤ tuple
python
CopyEdit
t = ("a", "b", "c", "d")
print(t[0]) # a
print(t[-1]) # d
print(t[1:3]) # ('b', 'c')
Mutable Yes No
Hashable No Yes
🔸 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
python
CopyEdit
t = (1, 2, 3, 2, 2)
print(t.count(2)) # 3
print(t.index(3)) # 2
🔸 7. Tuple Unpacking
python
CopyEdit
point = (10, 20)
x, y = point
print(x) # 10
print(y) # 20
🔸 8. Nested Tuples
python
CopyEdit
nested = ((1, 2), (3, 4))
print(nested[1][0]) # 3
python
CopyEdit
locations = {
(0, 0): "origin",
(1, 2): "point A"
}
🧠 Practice Tasks:
ChatGPT said:
🔹 1. Creating a Dictionary
python
CopyEdit
student = {
"name": "Alice",
"age": 20,
"marks": 85
}
🔹 2. Accessing Values
python
CopyEdit
print(student["name"]) # Alice
print(student["marks"]) # 85
Safer method:
python
CopyEdit
print(student.get("grade", "Not Found")) # Not Found
🔹 3. Adding & Updating Values
Update existing:
python
CopyEdit
student["marks"] = 90
python
CopyEdit
del student["age"]
student.pop("marks")
student.clear() # makes it {}
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)
🔹 8. Nested Dictionaries
python
CopyEdit
students = {
"s1": {"name": "Alice", "marks": 90},
"s2": {"name": "Bob", "marks": 85}
}
print(students["s1"]["marks"]) # 90
With condition:
python
CopyEdit
even_squares = {x: x*x for x in range(10) if x % 2 == 0}
🧠 Practice Tasks:
You said:
Continue
ChatGPT said:
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)
python
CopyEdit
empty_set = set() # NOT {}
🔹 2. No Duplicates Allowed
python
CopyEdit
nums = {1, 2, 2, 3, 4}
print(nums) # {1, 2, 3, 4}
These work:
python
CopyEdit
{1, "hello", (3, 4)}
This fails:
python
CopyEdit
{[1, 2]} # TypeError: unhashable type: 'list'
remove() vs discard()
python
CopyEdit
s.remove(4) # Error if not found
s.discard(4) # No error if not found
python
CopyEdit
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
Operation Code Result
Union `a bora.union(b)`
🔹 6. Set Comparisons
python
CopyEdit
a.issubset(b)
a.issuperset(b)
a.isdisjoint(b)
These return True or False.
python
CopyEdit
my_list = [1, 2, 2, 3]
no_duplicates = list(set(my_list))
python
CopyEdit
if 5 in my_set:
print("Found")
🧠 Practice Tasks:
You said:
Continue
ChatGPT said:
Excellent! Now we’re moving into one of the most important and frequently used data types:
python
CopyEdit
s1 = 'Hello'
s2 = "World"
s3 = '''Multi-line
string'''
Strings are immutable, indexable, iterable, and have many powerful methods.
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
python
CopyEdit
text = "Hello"
text[0] = "M" # Error: strings are immutable
python
CopyEdit
text = "M" + text[1:]
🔹 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))
🔹 5. Escape Characters
Code Meaning
\n Newline
\t Tab
\\ Backslash
python
CopyEdit
print("Hello\nWorld")
print("He said: \"Python is cool\"")
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
python
CopyEdit
text = """This is
a multi-line
string."""
🔹 9. String Comparisons
• == (equality)
• <, >, <=, >= (lexicographic order, like dictionary)
python
CopyEdit
print("apple" < "banana") # True
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.
Python offers multiple data structures — each with its own strengths and use cases.
1. Overview Table
Keys/Values No No No Yes
Use Case General data Fixed data Math, uniqueness Lookup, structured data
2. When to Use Lists
Use when:
python
CopyEdit
tasks = ["todo", "read", "code"]
tasks.append("eat")
Use when:
python
CopyEdit
coordinates = (10, 20)
Use when:
python
CopyEdit
colors = {"red", "green", "blue"}
colors.add("yellow")
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
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.
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:
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 {}
🔹 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
*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
outer()
🔹 12. Recursion
python
CopyEdit
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
python
CopyEdit
print(factorial(5)) # 120
Access with:
python
CopyEdit
print(greet.__doc__)
🧠 Practice Tasks
You said:
Continue
ChatGPT said:
Great! Now that you understand functions well, let’s move on to the next fundamental topic:
As your code grows, keeping everything in one file becomes messy. Python solves this using
modules and packages.
🔹 1. What is a Module?
def cube(n):
return n * n * n
python
CopyEdit
# main.py
import math_utils
print(math_utils.square(4)) # 16
print(math_utils.cube(3)) # 27
🔹 2. Importing Modules
Syntax Meaning
Examples:
python
CopyEdit
import math
print(math.sqrt(16))
import math as m
print(m.pi)
Module Purpose
Examples:
python
CopyEdit
import random
print(random.randint(1, 10))
import datetime
print(datetime.datetime.now())
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
Or:
python
CopyEdit
from mypackage.module2 import function_name
pip is Python’s package manager. You can use it to install third-party libraries.
Example:
bash
CopyEdit
pip install requests
python
CopyEdit
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
python
CopyEdit
# calculator.py
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(2, 3))
css
CopyEdit
project/
├── main.py
├── utils/
│ ├── __init__.py
│ ├── file_utils.py
│ └── math_utils.py
└── data/
python
CopyEdit
from utils.math_utils import square
🧠 Practice Tasks
Day 15: File Handling in Python — Reading, Writing, Appending, Working with Text and
CSV Files
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.
'a' Append
kotlin
CopyEdit
Hello world
Python is fun
readlines()
python
CopyEdit
lines = open("data.txt").readlines()
print(lines)
python
CopyEdit
file = open("newfile.txt", "w")
file.write("This is a new file.\n")
file.write("Second line.")
file.close()
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
Writing CSV:
python
CopyEdit
import csv
Reading CSV:
python
CopyEdit
import 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.
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:
OOP is a way of organizing code using classes and objects to model real-world things.
🔹 1. What is OOP?
• Attributes (data)
• Methods (functions)
# Creating objects
p1 = Person("Alice", 25)
p2 = Person("Bob", 30)
p1.greet()
p2.greet()
🔹 4. Understanding __init__() and self
Notation Meaning
python
CopyEdit
class Student:
def __init__(self, name):
self.__name = name # Private variable
def get_name(self):
return self.__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()
🔹 8. super() Function
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
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)
Method Purpose
__init__ Constructor
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
Day 17: Exception Handling — Try, Except, Else, Finally, Custom Errors
ChatGPT said:
Awesome! Let’s dive into the next essential topic that every robust Python program needs:
Errors happen — in user input, files, networks, etc. Exception handling helps you gracefully
handle errors without crashing your program.
Common examples:
• ZeroDivisionError
• FileNotFoundError
• ValueError
• TypeError
🔹 4. else Clause
python
CopyEdit
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print(f"You entered {num}")
🔹 5. finally Clause
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
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
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)
python
CopyEdit
try:
10 / 0
except ZeroDivisionError as e:
print(f"Error occurred: {e}")
python
CopyEdit
x = 5
assert x > 0, "x must be positive"
🧠 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.
Day 18: Working with Libraries — Using requests for HTTP, JSON Handling
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?
2. Installing 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)
5. POST Request
python
CopyEdit
data = {'username': 'alice', 'password': '1234'}
response = requests.post("https://httpbin.org/post", data=data)
print(response.json())
6. Handling JSON
python
CopyEdit
import json
data = {'name': 'Bob', 'age': 25}
json_str = json.dumps(data) # Python dict -> JSON string
print(json_str)
python
CopyEdit
headers = {'User-Agent': 'MyApp/1.0'}
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.
1. What is SQLite?
2. Connecting to a Database
python
CopyEdit
import sqlite3
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()
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()
python
CopyEdit
conn.close()
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
You said:
Continue
ChatGPT said:
Perfect! Let’s get into some of Python’s most elegant and powerful features: Decorators and
Generators.
1. Generators
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
python
CopyEdit
for num in count_up_to(3):
print(num)
2. Why Use Generators?
3. Generator Expressions
python
CopyEdit
gen = (x * x for x in range(5))
print(next(gen)) # 0
print(next(gen)) # 1
4. Decorators
@decorator_func
def say_hello():
print("Hello!")
say_hello()
Output:
pgsql
CopyEdit
Before the function runs.
Hello!
After the function runs.
python
CopyEdit
say_hello = decorator_func(say_hello)
@decorator_func
def greet(name):
print(f"Hello, {name}")
greet("Alice")
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)
python
CopyEdit
@decorator1
@decorator2
def func():
pass
Equivalent to:
python
CopyEdit
func = decorator1(decorator2(func))
10. Summary
🧠 Practice Tasks
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.
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
'a' Append
python
CopyEdit
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # strip removes newline chars
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.")
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.
python
CopyEdit
import json
# 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)
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
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.
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).
python
CopyEdit
class Dog:
def __init__(self, name, age):
self.name = name # attribute
self.age = age
dog1 = Dog("Buddy", 3)
dog1.bark() # Buddy says Woof!
cat1 = Cat("Whiskers", 2)
cat2 = Cat("Tom", 4)
print(cat1.species) # Felis catus
print(cat2.species) # Felis catus
5. Methods
@classmethod
def total_people(cls):
return cls.count
p1 = Person("Alice")
p2 = Person("Bob")
print(Person.total_people()) # 2
print(Math.add(5, 7)) # 12
8. Inheritance
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
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
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?
python
CopyEdit
def add(x, y):
return x + y
python
CopyEdit
import mymath
print(mymath.add(5, 3)) # 8
print(mymath.subtract(5, 3)) # 2
3. Import Variations
python
CopyEdit
from mymath import add
print(add(10, 4))
python
CopyEdit
from mymath import *
4. What is a Package?
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()
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
python
CopyEdit
from .math_ops import multiply # imports from same package
Example:
python
CopyEdit
from .math_ops import multiply
from .string_ops import to_upper
python
CopyEdit
from my_package import multiply, to_upper
• Python comes with many built-in modules like os, sys, random, datetime.
• Use them to avoid reinventing the wheel.
Example:
python
CopyEdit
import os
bash
CopyEdit
pip install requests
Use in code:
python
CopyEdit
import requests
response = requests.get('https://api.github.com')
print(response.status_code)
🧠 Practice Tasks
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
Note: Catching all exceptions is useful but can hide bugs if overused.
5. The else Clause
python
CopyEdit
try:
x = int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print(f"You entered {x}.")
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
python
CopyEdit
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
print(f"Age is {age}")
check_age(-1)
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
🧠 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.
• 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.
bash
CopyEdit
pip install requests
• Upgrade a library:
bash
CopyEdit
pip install --upgrade requests
• Uninstall a library:
bash
CopyEdit
pip uninstall requests
python
CopyEdit
import requests
response = requests.get('https://api.github.com')
print(response.status_code)
print(response.json())
bash
CopyEdit
python -m venv venv
• On Windows:
bash
CopyEdit
venv\Scripts\activate
• On macOS/Linux:
bash
CopyEdit
source venv/bin/activate
Simply run:
bash
CopyEdit
deactivate
bash
CopyEdit
pip freeze > requirements.txt
bash
CopyEdit
pip install -r requirements.txt
🧠 Practice Tasks
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.
1. Tuples
python
CopyEdit
t = (1, 2, 3)
print(t[0]) # 1
• Fixed data.
• Faster than lists.
• Can be used as dictionary keys (immutable).
Example:
python
CopyEdit
t = (1, 2, 3, 2)
print(t.count(2)) # 2
print(t.index(3)) # 2
2. Sets
python
CopyEdit
s = {1, 2, 3, 3, 4}
print(s) # {1, 2, 3, 4}
Set Operations
python
CopyEdit
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
python
CopyEdit
print(a & b) # {3}
python
CopyEdit
print(a - b) # {1, 2}
python
CopyEdit
print(a ^ b) # {1, 2, 4, 5}
Set Methods
python
CopyEdit
d = {'name': 'Alice', 'age': 25}
print(d['name']) # Alice
• Add or update:
python
CopyEdit
d['age'] = 26
d['city'] = 'New York'
• Remove:
python
CopyEdit
del d['city']
• Common methods:
Method Description
4. Dictionary Comprehension
python
CopyEdit
squares = {x: x*x for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Data Unique
Ordered? Mutable? Use Case
Structure Elements?
🧠 Practice Tasks
Ready for Day 27: File Operations Deep Dive and Working with CSV/JSON files?