├── .gitignore
├── 01_basics
├── __pycache__
│ └── hello_chai.cpython-312.pyc
├── chai.py
├── datatypes.md
└── hello_chai.py
├── 02_conditionals
├── 01_solution.py
├── 02_solution.py
├── 03_solution.py
├── 04_solution.py
├── 05_solution.py
├── 06_solution.py
├── 07_solution.py
├── 08_solution.py
├── 09_solution.py
└── questions.md
├── 03_loops
├── 01_solution.py
├── 02_solution.py
├── 03_solution.py
├── 04_solution.py
├── 05_solution.py
├── 06_solution.py
├── 07_solution.py
├── 08_solution.py
├── 09_solution.py
├── 10_solution.py
└── question.md
├── 04_iteration_tools
└── chai.py
├── 05_functions
├── 01_solution.py
├── 02_solution.py
├── 03_solution.py
├── 04_solution.py
├── 05_soulution.py
├── 06_solution.py
├── 07_solution.py
├── 08_solution.py
├── 09_solution.py
├── 10_solution.py
└── questions.md
├── 06_scopes
└── 01_scope.py
├── 07_oop
├── 01_solution.py
└── questions.md
├── 08_decorators
├── 01_solution.py
├── 02_solution.py
├── 03_solution.py
└── questions.md
├── 09_error_handling
├── error_handle.py
├── youtube.txt
└── youtube_manager.py
├── 10_database_sqlite3
├── youtube_manager_db.py
└── youtube_videos.db
├── 11_handling_apis
└── freeapi_username.py
├── 12_python_mongodb
└── youtube_manager_mongodb.py
├── 13_virtual_py
├── cheatsheet.md
└── requirement.txt
├── 14_jupyter_notes
├── chai.ipynb
└── conda_cheatsheet.md
└── readme.md
/.gitignore:
--------------------------------------------------------------------------------
1 | Ignore virtual env in any main or sub directory
2 |
3 | **/venv/
4 | **/.venv/
5 | # Operating system files
6 | .DS_Store
7 | Thumbs.db
8 |
9 | # IDE and editor files
10 | .vscode/
11 | .idea/
12 |
13 | # Build artifacts
14 | /build/
15 | /dist/
16 |
17 |
18 |
19 | # Logs and databases
20 | *.log
21 |
--------------------------------------------------------------------------------
/01_basics/__pycache__/hello_chai.cpython-312.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hiteshchoudhary/chai-aur-python/f78246570353066c55f6b4225e5731c9a6083a24/01_basics/__pycache__/hello_chai.cpython-312.pyc
--------------------------------------------------------------------------------
/01_basics/chai.py:
--------------------------------------------------------------------------------
1 | from hello_chai import chai
2 |
3 | chai("ginger tea")
4 |
5 | # this is comment
--------------------------------------------------------------------------------
/01_basics/datatypes.md:
--------------------------------------------------------------------------------
1 | # Object Types / Data Types
2 |
3 | - Number : 1234, 3.1415, 3+4j, 0b111, Decimal(), Fraction()
4 | - String : 'spam', "Bob's", b'a\x01c', u'sp\xc4m'
5 | - List : [1, [2, 'three'], 4.5], list(range(10))
6 | - Tuple : (1, 'spam', 4, 'U'), tuple('spam'), namedtuple
7 | - Dictionary : {'food': 'spam', 'taste': 'yum'}, dict(hours=10)
8 |
9 | - Set : set('abc'), {'a', 'b', 'c'}
10 |
11 | - File : open('eggs.txt'), open(r'C:\ham.bin', 'wb')
12 |
13 | - Boolean : True, False
14 | - None : None
15 | - Funtions, modules, classes
16 |
17 | - Advance: Decorators, Generators, Iterators, MetaProgramming
--------------------------------------------------------------------------------
/01_basics/hello_chai.py:
--------------------------------------------------------------------------------
1 | print("chai aur python")
2 |
3 | def chai(n):
4 | print(n)
5 |
6 | chai("lemon tea")
7 |
8 | chai_one = "lemon tea"
9 | chai_two = "ginger tea"
10 | chai_three = "masala chai"
--------------------------------------------------------------------------------
/02_conditionals/01_solution.py:
--------------------------------------------------------------------------------
1 | age = 65
2 |
3 | if age < 13:
4 | print("Child")
5 | elif age < 20:
6 | print("Teenager")
7 | elif age < 60:
8 | print("Adult")
9 | else:
10 | print("Senior")
--------------------------------------------------------------------------------
/02_conditionals/02_solution.py:
--------------------------------------------------------------------------------
1 | age = 26
2 | day = "Wednesday"
3 |
4 | price = 12 if age >= 18 else 8
5 |
6 | if day == "Wednesday":
7 | # price = price - 2
8 | price -= 2
9 |
10 | print("Ticket price for you is $",price)
--------------------------------------------------------------------------------
/02_conditionals/03_solution.py:
--------------------------------------------------------------------------------
1 | score = 185
2 |
3 | if score >= 101:
4 | print("Please verify your grade again")
5 | exit()
6 |
7 | if score >= 90:
8 | grade = "A"
9 | elif score >= 80:
10 | grade = "B"
11 | elif score >= 70:
12 | grade = "C"
13 | elif score >= 60:
14 | grade = "D"
15 | else:
16 | grade = "F"
17 |
18 | print("Grade: ", grade)
--------------------------------------------------------------------------------
/02_conditionals/04_solution.py:
--------------------------------------------------------------------------------
1 | fruit = "Banana"
2 | color = "Yellow"
3 |
4 | if fruit == "Banana":
5 | if color == "Green":
6 | print("Unripe")
7 | elif color == "Yellow":
8 | print("Ripe")
9 | elif color == "Brown":
10 | print("OverRipe")
11 |
12 |
--------------------------------------------------------------------------------
/02_conditionals/05_solution.py:
--------------------------------------------------------------------------------
1 | weather = "Sunny"
2 |
3 | if weather == "Sunny":
4 | activity = "Go for a walk"
5 | elif weather == "Rainy":
6 | activity = "Read a book"
7 | elif weather == "Snowy":
8 | activity = "Build a snowman"
9 |
10 | print(activity)
--------------------------------------------------------------------------------
/02_conditionals/06_solution.py:
--------------------------------------------------------------------------------
1 | distance = 5
2 |
3 | if distance < 3:
4 | transport = "Walk"
5 | elif distance <= 15:
6 | transport = "Bike"
7 | else:
8 | transport = "Car"
9 |
10 | print("AI recommends you the transport of: ", transport)
11 |
--------------------------------------------------------------------------------
/02_conditionals/07_solution.py:
--------------------------------------------------------------------------------
1 | order_size = "Medium"
2 | extra_shot = True
3 |
4 | if extra_shot:
5 | coffee = order_size + " coffee with an extra shot"
6 | else:
7 | coffee = order_size + " coffee"
8 |
9 | print("Order: ", coffee)
--------------------------------------------------------------------------------
/02_conditionals/08_solution.py:
--------------------------------------------------------------------------------
1 | password = "Secure3P@ss"
2 | password_length = len(password)
3 |
4 | if len(password) < 6:
5 | strength = "Weak"
6 | elif len(password) <= 10:
7 | strength = "Medium"
8 | else:
9 | strength = "Strong"
10 |
11 | print("Password strength is: ", strength)
--------------------------------------------------------------------------------
/02_conditionals/09_solution.py:
--------------------------------------------------------------------------------
1 | year = 2023
2 |
3 | if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
4 | print( year, " is a leap year")
5 | else:
6 | print(year, "is NOT a leap year")
--------------------------------------------------------------------------------
/02_conditionals/questions.md:
--------------------------------------------------------------------------------
1 | # questions on conditionals
2 |
3 |
4 | 1. Age Group Categorization
5 |
6 | Classify a person's age group: Child (< 13), Teenager (13-19), Adult (20-59), Senior (60+).
7 |
8 |
9 |
10 |
11 | 2. Movie Ticket Pricing
12 |
13 | Problem: Movie tickets are priced based on age: $12 for adults (18 and over), $8 for children. Everyone gets a $2 discount on Wednesday.
14 |
15 |
16 |
17 |
18 | 3. Grade Calculator
19 |
20 | Problem: Assign a letter grade based on a student's score: A (90-100), B (80-89), C (70-79), D (60-69), F (below 60).
21 |
22 |
23 |
24 |
25 | 4. Fruit Ripeness Checker
26 |
27 | Problem: Determine if a fruit is ripe, overripe, or unripe based on its color. (e.g., Banana: Green - Unripe, Yellow - Ripe, Brown - Overripe)
28 |
29 |
30 |
31 |
32 | 5. Weather Activity Suggestion
33 |
34 | Problem: Suggest an activity based on the weather (e.g., Sunny - Go for a walk, Rainy - Read a book, Snowy - Build a snowman).
35 |
36 |
37 |
38 |
39 | 6. Transportation Mode Selection
40 |
41 | Problem: Choose a mode of transportation based on the distance (e.g., <3 km: Walk, 3-15 km: Bike, >15 km: Car).
42 |
43 |
44 |
45 |
46 |
47 | 7. Coffee Customization
48 |
49 | Problem: Customize a coffee order: "Small", "Medium", or "Large" with an option for "Extra shot" of espresso.
50 |
51 |
52 |
53 |
54 |
55 | 8. Password Strength Checker
56 |
57 | Problem: Check if a password is "Weak", "Medium", or "Strong". Criteria: < 6 chars (Weak), 6-10 chars (Medium), >10 chars (Strong).
58 |
59 |
60 |
61 |
62 |
63 | 9. Leap Year Checker
64 |
65 | Problem: Determine if a year is a leap year. (Leap years are divisible by 4, but not by 100 unless also divisible by 400).
66 |
67 |
68 |
69 |
70 |
71 | 10. Pet Food Recommendation
72 |
73 | Problem: Recommend a type of pet food based on the pet's species and age. (e.g., Dog: <2 years - Puppy food, Cat: >5 years - Senior cat food).
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/03_loops/01_solution.py:
--------------------------------------------------------------------------------
1 | numbers = [1, -2, 3, -4, 5, 6, -7, -8, 9, 10]
2 | positive_number_count = 0
3 | for num in numbers:
4 | if num > 0:
5 | positive_number_count += 1
6 | print("Final count of Positive number is: ", positive_number_count)
--------------------------------------------------------------------------------
/03_loops/02_solution.py:
--------------------------------------------------------------------------------
1 | n = 10
2 | sum_even = 0
3 |
4 | for i in range(1, n+1):
5 | if i%2 == 0:
6 | sum_even += 1
7 |
8 | print("Sum of even number is: , ", sum_even)
--------------------------------------------------------------------------------
/03_loops/03_solution.py:
--------------------------------------------------------------------------------
1 | number = 3
2 |
3 | for i in range(1, 11):
4 | if i == 5:
5 | continue
6 | print(number, 'x', i, '=', number * i)
7 |
8 |
--------------------------------------------------------------------------------
/03_loops/04_solution.py:
--------------------------------------------------------------------------------
1 | input_str = "Python"
2 | reversed_str = ""
3 |
4 | for char in input_str:
5 | reversed_str = char + reversed_str
6 |
7 | print(reversed_str)
--------------------------------------------------------------------------------
/03_loops/05_solution.py:
--------------------------------------------------------------------------------
1 | input_str = "teeteracdacd"
2 |
3 | for char in input_str:
4 | print(char)
5 | if input_str.count(char) == 1:
6 | print("Char is: ", char)
7 | break
--------------------------------------------------------------------------------
/03_loops/06_solution.py:
--------------------------------------------------------------------------------
1 | number = 5
2 | factorial = 1
3 |
4 | while number > 0:
5 | # factorial = factorial * number
6 | # number = number - 1
7 | factorial *= number
8 | number -= 1
9 |
10 | print("Factorial: ", factorial)
--------------------------------------------------------------------------------
/03_loops/07_solution.py:
--------------------------------------------------------------------------------
1 | while True:
2 | number = int(input("Enter value b/w 1 and 10: "))
3 | if 1 <= number <= 10:
4 | print("Thanks")
5 | break
6 | else:
7 | print("Invalid number, try again")
--------------------------------------------------------------------------------
/03_loops/08_solution.py:
--------------------------------------------------------------------------------
1 | number = 28
2 |
3 | is_prime = True
4 |
5 | if number > 1:
6 | for i in range(2, number):
7 | if (number % i) == 0:
8 | is_prime = False
9 | break
10 |
11 | print(is_prime)
--------------------------------------------------------------------------------
/03_loops/09_solution.py:
--------------------------------------------------------------------------------
1 | items = ["apple", "banana", "orange", "apple", "mango"]
2 |
3 | unique_item = set()
4 |
5 | for item in items:
6 | if item in unique_item:
7 | print("Duplicate: ", item)
8 | break
9 | unique_item.add(item)
--------------------------------------------------------------------------------
/03_loops/10_solution.py:
--------------------------------------------------------------------------------
1 | import time
2 |
3 | wait_time = 1
4 | max_retries = 5
5 | attempts = 0
6 |
7 | while attempts < max_retries:
8 | print("Attempt", attempts + 1, "- wait time", wait_time, )
9 | time.sleep(wait_time)
10 | wait_time *= 2
11 | attempts += 1
--------------------------------------------------------------------------------
/03_loops/question.md:
--------------------------------------------------------------------------------
1 | # Loops in Python
2 |
3 |
4 |
5 | 1. Counting Positive Numbers
6 |
7 | Problem: Given a list of numbers, count how many are positive.
8 |
9 | ```python
10 | numbers = [1, -2, 3, -4, 5, 6, -7, -8, 9, 10]
11 | ```
12 |
13 |
14 |
15 |
16 |
17 |
18 | 2. Sum of Even Numbers
19 |
20 | Problem: Calculate the sum of even numbers up to a given number n.
21 |
22 |
23 |
24 |
25 |
26 |
27 | 3. Multiplication Table Printer
28 |
29 | Problem: Print the multiplication table for a given number up to 10, but skip the fifth iteration.
30 |
31 |
32 |
33 |
34 |
35 |
36 | 4. Reverse a String
37 |
38 | Problem: Reverse a string using a loop.
39 |
40 |
41 |
42 |
43 |
44 |
45 | 5. Find the First Non-Repeated Character
46 |
47 | Problem: Given a string, find the first non-repeated character.
48 |
49 |
50 |
51 |
52 |
53 |
54 | 6. Factorial Calculator
55 |
56 | Problem: Compute the factorial of a number using a while loop.
57 |
58 |
59 |
60 |
61 |
62 |
63 | 7. Validate Input
64 |
65 | Problem: Keep asking the user for input until they enter a number between 1 and 10.
66 |
67 |
68 |
69 |
70 |
71 |
72 | 8. Prime Number Checker
73 |
74 | Problem: Check if a number is prime.
75 |
76 |
77 |
78 |
79 |
80 |
81 | 9. List Uniqueness Checker
82 |
83 | Problem: Check if all elements in a list are unique. If a duplicate is found, exit the loop and print the duplicate.
84 |
85 | ```python
86 | items = ["apple", "banana", "orange", "apple", "mango"]
87 | ```
88 |
89 |
90 |
91 |
92 |
93 | 10. Exponential Backoff
94 |
95 | Problem: Implement an exponential backoff strategy that doubles the wait time between retries, starting from 1 second, but stops after 5 retries.
96 |
97 |
98 |
--------------------------------------------------------------------------------
/04_iteration_tools/chai.py:
--------------------------------------------------------------------------------
1 | import time
2 | print("chai is here")
3 | username = "hitesh"
4 | print(username)
--------------------------------------------------------------------------------
/05_functions/01_solution.py:
--------------------------------------------------------------------------------
1 | def square(number):
2 | return number ** 2
3 |
4 |
5 | result = square(4)
6 | print(16)
7 |
--------------------------------------------------------------------------------
/05_functions/02_solution.py:
--------------------------------------------------------------------------------
1 | def add(numOne, numTwo):
2 | return numOne + numTwo
3 |
4 |
5 | print(add(5, 5))
--------------------------------------------------------------------------------
/05_functions/03_solution.py:
--------------------------------------------------------------------------------
1 | def multiply(p1, p2):
2 | return p1 * p2
3 |
4 |
5 | print(multiply(8, 5))
6 | print(multiply('a', 5))
7 | print(multiply(5, 'a'))
--------------------------------------------------------------------------------
/05_functions/04_solution.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | def circle_stats(radius):
4 | area = math.pi * radius ** 2
5 | circumference = 2 * math.pi * radius
6 | return area, circumference
7 |
8 | a, c = circle_stats(3)
9 |
10 | print("Area: ", a, "Circumference: ", c)
--------------------------------------------------------------------------------
/05_functions/05_soulution.py:
--------------------------------------------------------------------------------
1 | def greet(name = "User"):
2 | return "Hello, " + name + " !"
3 |
4 |
5 | print(greet("chai"))
6 | print(greet())
--------------------------------------------------------------------------------
/05_functions/06_solution.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | cube = lambda x: x ** 3
5 |
6 | print(cube(3))
--------------------------------------------------------------------------------
/05_functions/07_solution.py:
--------------------------------------------------------------------------------
1 | def sum_all(*args):
2 | print(args)
3 | for i in args:
4 | print(i * 2)
5 | return sum(args)
6 |
7 | print(sum_all(1, 2, 3))
8 | # print(sum_all(1, 2, 3, 4, 5))
9 | # print(sum_all(1, 2, 3, 4, 5, 6, 7, 8))
--------------------------------------------------------------------------------
/05_functions/08_solution.py:
--------------------------------------------------------------------------------
1 | def print_kwargs(**kwargs):
2 | for key, value in kwargs.items():
3 | print(f"{key}: {value}")
4 |
5 |
6 | print_kwargs(name="shaktiman", power="lazer")
7 | print_kwargs(name="shaktiman")
8 | print_kwargs(name="shaktiman", power="lazer", enemy = "Dr. Jackaal")
--------------------------------------------------------------------------------
/05_functions/09_solution.py:
--------------------------------------------------------------------------------
1 | def even_generator(limit):
2 | for i in range(2, limit + 1, 2):
3 | yield i
4 |
5 |
6 |
7 | for num in even_generator(10):
8 | print(num)
--------------------------------------------------------------------------------
/05_functions/10_solution.py:
--------------------------------------------------------------------------------
1 | def factorial(n):
2 | if n == 0:
3 | return 1
4 | else:
5 | return n * factorial(n - 1)
--------------------------------------------------------------------------------
/05_functions/questions.md:
--------------------------------------------------------------------------------
1 | # Learn all about functions by answering the questions below.
2 |
3 |
4 |
5 |
6 | 1. Basic Function Syntax
7 |
8 | Problem: Write a function to calculate and return the square of a number.
9 |
10 |
11 |
12 |
13 |
14 | 2. Function with Multiple Parameters
15 |
16 | Problem: Create a function that takes two numbers as parameters and returns their sum.
17 |
18 |
19 |
20 |
21 |
22 | 3. Polymorphism in Functions
23 |
24 | Problem: Write a function multiply that multiplies two numbers, but can also accept and multiply strings.
25 |
26 |
27 |
28 |
29 |
30 | 4. Function Returning Multiple Values
31 |
32 | Problem: Create a function that returns both the area and circumference of a circle given its radius.
33 |
34 |
35 |
36 |
37 |
38 | 5. Default Parameter Value
39 |
40 | Problem: Write a function that greets a user. If no name is provided, it should greet with a default name.
41 |
42 |
43 |
44 |
45 |
46 | 6. Lambda Function
47 |
48 | Problem: Create a lambda function to compute the cube of a number.
49 |
50 |
51 |
52 |
53 |
54 | 7. Function with *args
55 |
56 | Problem: Write a function that takes variable number of arguments and returns their sum.
57 |
58 |
59 |
60 |
61 |
62 | 8. Function with **kwargs
63 |
64 | Problem: Create a function that accepts any number of keyword arguments and prints them in the format key: value.
65 |
66 |
67 |
68 |
69 |
70 | 9. Generator Function with yield
71 |
72 | Problem: Write a generator function that yields even numbers up to a specified limit.
73 |
74 |
75 |
76 |
77 |
78 | 10. Recursive Function
79 |
80 | Problem: Create a recursive function to calculate the factorial of a number.
81 |
82 |
83 |
--------------------------------------------------------------------------------
/06_scopes/01_scope.py:
--------------------------------------------------------------------------------
1 | username = "chaiaurcode"
2 |
3 | def func():
4 | # username = "chai"
5 | print(username)
6 |
7 | print(username)
8 | func()
9 |
10 |
11 | x = 99
12 | # def func2(y):
13 | # z = x + y
14 | # return z
15 |
16 | # result = func2(1)
17 | # print(result)
18 |
19 | # def func3():
20 | # global x
21 | # x = 12
22 |
23 | # func3()
24 | # print(x)
25 |
26 |
27 |
28 | def f1():
29 | x = 88
30 | def f2():
31 | print(x)
32 | return f2
33 | myResult = f1()
34 | myResult()
35 |
36 |
37 | def chaicoder(num):
38 | def actual(x):
39 | return x ** num
40 | return actual
41 |
42 |
43 |
44 | f = chaicoder(2)
45 | g = chaicoder(3)
46 |
47 | print(f(3))
48 | print(g(3))
--------------------------------------------------------------------------------
/07_oop/01_solution.py:
--------------------------------------------------------------------------------
1 | class Car:
2 | total_car = 0
3 |
4 | def __init__(self, brand, model):
5 | self.__brand = brand
6 | self.__model = model
7 | Car.total_car += 1
8 |
9 | def get_brand(self):
10 | return self.__brand + " !"
11 |
12 | def full_name(self):
13 | return f"{self.__brand} {self.__model}"
14 |
15 | def fuel_type(self):
16 | return "Petrol or Diesel"
17 |
18 | @staticmethod
19 | def general_description():
20 | return "Cars are means of transport"
21 |
22 | @property
23 | def model(self):
24 | return self.__model
25 |
26 |
27 |
28 | class ElectricCar(Car):
29 | def __init__(self, brand, model, battery_size):
30 | super().__init__(brand, model)
31 | self.battery_size = battery_size
32 |
33 | def fuel_type():
34 | return "Electric charge"
35 |
36 |
37 | # my_tesla = ElectricCar("Tesla", "Model S", "85kWh")
38 |
39 | # print(isinstance(my_tesla, Car))
40 | # print(isinstance(my_tesla, ElectricCar))
41 |
42 | # print(my_tesla.__brand)
43 | # print(my_tesla.fuel_type())
44 |
45 | # my_car = Car("Tata", "Safari")
46 | # my_car.model = "City"
47 | # Car("Tata", "Nexon")
48 |
49 |
50 | # print(my_car.general_description())
51 | # print(my_car.model)
52 |
53 |
54 | # my_car = Car("Toyota", "Corolla")
55 | # print(my_car.brand)
56 | # print(my_car.model)
57 | # print(my_car.full_name())
58 |
59 | # my_new_car = Car("Tata", "Safari")
60 | # print(my_new_car.model)
61 |
62 |
63 |
64 | class Battery:
65 | def battery_info(self):
66 | return "this is battery"
67 |
68 | class Engine:
69 | def engine_info(self):
70 | return "This is engine"
71 |
72 | class ElectricCarTwo(Battery, Engine, Car):
73 | pass
74 |
75 | my_new_tesla = ElectricCarTwo("Tesla", "Model S")
76 | print(my_new_tesla.engine_info())
77 | print(my_new_tesla.battery_info())
--------------------------------------------------------------------------------
/07_oop/questions.md:
--------------------------------------------------------------------------------
1 | # learn about Object Oriented Programming by answering these questions
2 |
3 |
4 |
5 |
6 | 1. Basic Class and Object
7 |
8 | Problem: Create a Car class with attributes like brand and model. Then create an instance of this class.
9 |
10 |
11 |
12 |
13 |
14 | 2. Class Method and Self
15 |
16 | Problem: Add a method to the Car class that displays the full name of the car (brand and model).
17 |
18 |
19 |
20 |
21 |
22 | 3. Inheritance
23 |
24 | Problem: Create an ElectricCar class that inherits from the Car class and has an additional attribute battery_size.
25 |
26 |
27 |
28 |
29 |
30 |
31 | 4. Encapsulation
32 |
33 | Problem: Modify the Car class to encapsulate the brand attribute, making it private, and provide a getter method for it.
34 |
35 |
36 |
37 |
38 | 5. Polymorphism
39 |
40 | Problem: Demonstrate polymorphism by defining a method fuel_type in both Car and ElectricCar classes, but with different behaviors.
41 |
42 |
43 |
44 |
45 |
46 |
47 | 6. Class Variables
48 |
49 | Problem: Add a class variable to Car that keeps track of the number of cars created.
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | 7. Static Method
58 |
59 | Problem: Add a static method to the Car class that returns a general description of a car.
60 |
61 |
62 |
63 |
64 |
65 |
66 | 8. Property Decorators
67 |
68 | Problem: Use a property decorator in the Car class to make the model attribute read-only.
69 |
70 |
71 |
72 |
73 |
74 |
75 | 9. Class Inheritance and isinstance() Function
76 |
77 | Problem: Demonstrate the use of isinstance() to check if my_tesla is an instance of Car and ElectricCar.
78 |
79 |
80 |
81 |
82 |
83 |
84 | 10. Multiple Inheritance
85 |
86 | Problem: Create two classes Battery and Engine, and let the ElectricCar class inherit from both, demonstrating multiple inheritance.
87 |
88 |
89 |
90 |
--------------------------------------------------------------------------------
/08_decorators/01_solution.py:
--------------------------------------------------------------------------------
1 | import time
2 |
3 | def timer(func):
4 | def wrapper(*args, **kwargs):
5 | start = time.time()
6 | result = func(*args, **kwargs)
7 | end = time.time()
8 | print(f"{func.__name__} ran in {end-start} time")
9 | return result
10 | return wrapper
11 |
12 |
13 | @timer
14 | def example_function(n):
15 | time.sleep(n)
16 |
17 | example_function(2)
--------------------------------------------------------------------------------
/08_decorators/02_solution.py:
--------------------------------------------------------------------------------
1 |
2 | def debug(func):
3 | def wrapper(*args, **kwargs):
4 | args_value = ', '.join(str(arg) for arg in args)
5 | kwargs_value = ', '.join(f"{k}={v}" for k, v in kwargs.
6 | items())
7 | print(f"calling: {func.__name__} with args {args_value} and kwargs {kwargs_value}")
8 | return func(*args, **kwargs)
9 |
10 | return wrapper
11 |
12 | @debug
13 | def hello():
14 | print("hello")
15 |
16 | @debug
17 | def greet(name, greeting="Hello"):
18 | print(f"{greeting}, {name}")
19 |
20 | hello()
21 | greet("chai", greeting="hanji ")
--------------------------------------------------------------------------------
/08_decorators/03_solution.py:
--------------------------------------------------------------------------------
1 | import time
2 |
3 | def cache(func):
4 | cache_value = {}
5 | print(cache_value)
6 | def wrapper(*args):
7 | if args in cache_value:
8 | return cache_value[args]
9 | result = func(*args)
10 | cache_value[args] = result
11 | return result
12 | return wrapper
13 |
14 | @cache
15 | def long_running_function(a, b):
16 | time.sleep(4)
17 | return a + b
18 |
19 | print(long_running_function(2, 3))
20 | print(long_running_function(2, 3))
21 | print(long_running_function(4, 3))
--------------------------------------------------------------------------------
/08_decorators/questions.md:
--------------------------------------------------------------------------------
1 | # learn about decorators
2 |
3 |
4 |
5 |
6 | Problem 1: Timing Function Execution
7 |
8 | Problem: Write a decorator that measures the time a function takes to execute.
9 |
10 |
11 |
12 |
13 |
14 | Problem 2: Debugging Function Calls
15 |
16 | Problem: Create a decorator to print the function name and the values of its arguments every time the function is called.
17 |
18 |
19 |
20 |
21 |
22 | Problem 3: Cache Return Values
23 |
24 | Problem: Implement a decorator that caches the return values of a function, so that when it's called with the same arguments, the cached value is returned instead of re-executing the function.
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/09_error_handling/error_handle.py:
--------------------------------------------------------------------------------
1 | file = open('youtube.txt', 'w')
2 |
3 | try:
4 | file.write('chai aur code')
5 | finally:
6 | file.close()
7 |
8 | with open('youtube.txt', 'w') as file:
9 | file.write('chai aur python')
--------------------------------------------------------------------------------
/09_error_handling/youtube.txt:
--------------------------------------------------------------------------------
1 | [{"name": "chai aur python", "time": "50 mins"}, {"name": "chai aur javascript", "time": "14 hours"}]
--------------------------------------------------------------------------------
/09_error_handling/youtube_manager.py:
--------------------------------------------------------------------------------
1 |
2 | import json
3 |
4 | def load_data():
5 | try:
6 | with open('youtube.txt', 'r') as file:
7 | test = json.load(file)
8 | # print(type(test))
9 | return test
10 | except FileNotFoundError:
11 | return []
12 |
13 | def save_data_helper(videos):
14 | with open('youtube.txt', 'w') as file:
15 | json.dump(videos, file)
16 |
17 | def list_all_videos(videos):
18 | print("\n")
19 | print("*" * 70)
20 | for index, video in enumerate(videos, start=1):
21 | print(f"{index}. {video['name']}, Duration: {video['time']} ")
22 | print("\n")
23 | print("*" * 70)
24 |
25 | def add_video(videos):
26 | name = input("Enter video name: ")
27 | time = input("Enter video time: ")
28 | videos.append({'name': name, 'time': time})
29 | save_data_helper(videos)
30 |
31 | def update_video(videos):
32 | list_all_videos(videos)
33 | index = int(input("Enter the video number to update"))
34 | if 1 <= index <= len(videos):
35 | name = input("Enter the new video name")
36 | time = input("Enter the new video time")
37 | videos[index-1] = {'name':name, 'time': time}
38 | save_data_helper(videos)
39 | else:
40 | print("Invalid index selected")
41 |
42 |
43 | def delete_video(videos):
44 | list_all_videos(videos)
45 | index = int(input("Enter the video number to be deleted"))
46 |
47 | if 1<= index <= len(videos):
48 | del videos[index-1]
49 | save_data_helper(videos)
50 | else:
51 | print("Invalid video index selected")
52 |
53 |
54 | def main():
55 | videos = load_data()
56 | while True:
57 | print("\n Youtube Manager | choose an option ")
58 | print("1. List all youtube videos ")
59 | print("2. Add a youtube video ")
60 | print("3. Update a youtube video details ")
61 | print("4. Delete a youtube video ")
62 | print("5. Exit the app ")
63 | choice = input("Enter your choice: ")
64 | # print(videos)
65 |
66 | match choice:
67 | case '1':
68 | list_all_videos(videos)
69 | case '2':
70 | add_video(videos)
71 | case '3':
72 | update_video(videos)
73 | case '4':
74 | delete_video(videos)
75 | case '5':
76 | break
77 | case _:
78 | print("Invalid Choice")
79 |
80 | if __name__ == "__main__":
81 | main()
82 |
83 |
84 |
--------------------------------------------------------------------------------
/10_database_sqlite3/youtube_manager_db.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 |
3 | conn = sqlite3.connect('youtube_videos.db')
4 |
5 | cursor = conn.cursor()
6 |
7 | cursor.execute('''
8 | CREATE TABLE IF NOT EXISTS videos (
9 | id INTEGER PRIMARY KEY,
10 | name TEXT NOT NULL,
11 | time TEXT NOT NULL
12 | )
13 | ''')
14 |
15 | def list_videos():
16 | cursor.execute("SELECT * FROM videos")
17 | for row in cursor.fetchall():
18 | print(row)
19 |
20 | def add_video(name, time):
21 | cursor.execute("INSERT INTO videos (name, time) VALUES (?, ?)", (name, time))
22 | conn.commit()
23 |
24 | def update_video(video_id, new_name, new_time):
25 | cursor.execute("UPDATE videos SET name = ?, time = ? WHERE id = ?", (new_name, new_time, video_id))
26 | conn.commit()
27 |
28 | def delete_video(video_id):
29 | cursor.execute("DELETE FROM videos where id = ?", (video_id,))
30 | conn.commit()
31 |
32 | def main():
33 | while True:
34 | print("\n Youtube manager app with DB")
35 | print("1. List Videos")
36 | print("2. Add Videos")
37 | print("3. Update Videos")
38 | print("4. Delete Videos")
39 | print("5. exit app")
40 | choice = input("Enter your choice: ")
41 |
42 | if choice == '1':
43 | list_videos()
44 | elif choice == '2':
45 | name = input("Enter the video name: ")
46 | time = input("Enter the video time: ")
47 | add_video(name, time)
48 | elif choice == '3':
49 | video_id = input("Enter video ID to update: ")
50 | name = input("Enter the video name: ")
51 | time = input("Enter the video time: ")
52 | update_video(video_id, name, time)
53 | elif choice == '4':
54 | video_id = input("Enter video ID to delete: ")
55 | delete_video(video_id)
56 | elif choice == '5':
57 | break
58 | else:
59 | print("Invalid Choice ")
60 |
61 | conn.close()
62 |
63 | if __name__ == "__main__":
64 | main()
--------------------------------------------------------------------------------
/10_database_sqlite3/youtube_videos.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hiteshchoudhary/chai-aur-python/f78246570353066c55f6b4225e5731c9a6083a24/10_database_sqlite3/youtube_videos.db
--------------------------------------------------------------------------------
/11_handling_apis/freeapi_username.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | def fectch_random_user_freeapi():
4 | url = "https://api.freeapi.app/api/v1/public/randomusers/user/random"
5 | response = requests.get(url)
6 | data = response.json()
7 |
8 | if data["success"] and "data" in data:
9 | user_data = data["data"]
10 | username = user_data["login"]["username"]
11 | country = user_data["location"]["country"]
12 | return username, country
13 | else:
14 | raise Exception("Failed to fetch user data")
15 |
16 |
17 | def main():
18 | try:
19 | username, country = fectch_random_user_freeapi()
20 | print(f"Username: {username} \nCountry: {country}")
21 | except Exception as e:
22 | print(str(e))
23 |
24 | if __name__ == "__main__":
25 | main()
--------------------------------------------------------------------------------
/12_python_mongodb/youtube_manager_mongodb.py:
--------------------------------------------------------------------------------
1 | from pymongo import MongoClient
2 | from bson import ObjectId
3 |
4 | client = MongoClient("mongodb+srv://CHAI:CHAI@cluster0.lxl3fsq.mongodb.net/", tlsAllowInvalidCertificates=True)
5 | # Not a good idea to include id and password in code files
6 | # tlsAllowInvalidCertificates=True - Not a good way to handle ssl
7 |
8 | print(client)
9 | db = client["ytmanager"]
10 | video_collection = db["videos"]
11 |
12 | # print(video_collection)
13 |
14 | def add_video(name, time):
15 | video_collection.insert_one({"name": name, "time": time})
16 |
17 | def list_videos():
18 | for video in video_collection.find():
19 | print(f"ID: {video['_id']}, Name: {video['name']} and Time: {video['time']}")
20 |
21 | def update_video(video_id, new_name, new_time):
22 | video_collection.update_one({'_id': ObjectId(video_id)}, {"$set": {"name": new_name, "time": new_time}})
23 |
24 | def delete_video(video_id):
25 | video_collection.delete_one({"_id": video_id})
26 | # TODO: debug this video_id problem
27 |
28 |
29 | def main():
30 | while True:
31 | print("\n Youtube manager App")
32 | print("1. List all videos")
33 | print("2. Add a new videos")
34 | print("3. Update a videos")
35 | print("4. Delete a videos")
36 | print("5. Exit the app")
37 | choice = input("Enter your choice: ")
38 |
39 | if choice == '1':
40 | list_videos()
41 | elif choice == '2':
42 | name = input("Enter the video name: ")
43 | time = input("Enter the video time: ")
44 | add_video(name, time)
45 | elif choice == '3':
46 | video_id = input("Enter the video id to update: ")
47 | name = input("Enter the updated video name: ")
48 | time = input("Enter the updated video time: ")
49 | update_video(video_id, name, time)
50 | elif choice == '4':
51 | video_id = input("Enter the video id to update: ")
52 | delete_video(video_id, name, time)
53 | elif choice == '5':
54 | break
55 | else:
56 | print("Invalid choice")
57 |
58 | if __name__ == "__main__":
59 | main()
--------------------------------------------------------------------------------
/13_virtual_py/cheatsheet.md:
--------------------------------------------------------------------------------
1 | # python virtual environment cheatsheet
2 |
3 | ## Create a new virtual environment
4 | `python -m venv env_name`
5 |
6 | ## Install packages
7 | `pip install package_name`
8 |
9 | ## Save installed packages to a file
10 | `pip freeze > requirements.txt`
11 | or
12 | `pip list --format=freeze > requirements.txt`
13 |
14 | ## Install packages from a file
15 | `pip install -r requirements.txt`
16 |
17 | ## Deactivate the current virtual environment
18 | `deactivate`
19 |
20 |
21 |
22 | ## In Linux or Mac, activate the new python environment
23 | `source env_name/bin/activate`
24 | ## Or in Windows
25 | `.\env_name\Scripts\activate`
--------------------------------------------------------------------------------
/13_virtual_py/requirement.txt:
--------------------------------------------------------------------------------
1 | Package Version
2 | --------- -------
3 | asgiref 3.7.2
4 | Django 5.0.1
5 | dnspython 2.5.0
6 | pip 23.2.1
7 | sqlparse 0.4.4
8 |
--------------------------------------------------------------------------------
/14_jupyter_notes/chai.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 2,
6 | "metadata": {},
7 | "outputs": [
8 | {
9 | "name": "stdout",
10 | "output_type": "stream",
11 | "text": [
12 | "chai aur code\n"
13 | ]
14 | }
15 | ],
16 | "source": [
17 | "print(\"chai aur code\")"
18 | ]
19 | },
20 | {
21 | "cell_type": "markdown",
22 | "metadata": {},
23 | "source": [
24 | "### chai aur python\n",
25 | "this is core python learning\n",
26 | "\n",
27 | "---\n"
28 | ]
29 | },
30 | {
31 | "cell_type": "code",
32 | "execution_count": 3,
33 | "metadata": {},
34 | "outputs": [
35 | {
36 | "name": "stdout",
37 | "output_type": "stream",
38 | "text": [
39 | "0-1-2-3-4-5-6-"
40 | ]
41 | }
42 | ],
43 | "source": [
44 | "for i in range(7):\n",
45 | " print(i, end=\"-\")"
46 | ]
47 | }
48 | ],
49 | "metadata": {
50 | "kernelspec": {
51 | "display_name": "py310",
52 | "language": "python",
53 | "name": "python3"
54 | },
55 | "language_info": {
56 | "codemirror_mode": {
57 | "name": "ipython",
58 | "version": 3
59 | },
60 | "file_extension": ".py",
61 | "mimetype": "text/x-python",
62 | "name": "python",
63 | "nbconvert_exporter": "python",
64 | "pygments_lexer": "ipython3",
65 | "version": "3.10.13"
66 | }
67 | },
68 | "nbformat": 4,
69 | "nbformat_minor": 2
70 | }
71 |
--------------------------------------------------------------------------------
/14_jupyter_notes/conda_cheatsheet.md:
--------------------------------------------------------------------------------
1 | # conda cheatsheet
2 |
3 | ## Create a new environment
4 | ```bash
5 | conda create --name myenv python=3.6
6 | ```
7 |
8 | ## Activate an environment
9 |
10 | ```bash
11 | conda activate myenv
12 | ```
13 |
14 | ## Deactivate an environment
15 |
16 | ```bash
17 | conda deactivate
18 | ```
19 |
20 | ## Delete an environment
21 |
22 | ```bash
23 | conda remove --name myenv --all
24 | ```
25 |
26 | ## Install a package
27 |
28 | ```bash
29 | conda install --name myenv numpy
30 | ```
31 |
32 | ## List all packages installed in an environment
33 |
34 | ```bash
35 | conda list --name myenv
36 | ```
37 |
38 | ## List all environments
39 |
40 | ```bash
41 | conda info --envs
42 | ```
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # welcome to the python series | chai aur python
2 |
3 | Hanji, ye python ki series hai, jisme hum python ke bare me seekhenge. Ye series hindi me hai, jisse aapko samajhne me aasani hogi. Ye series kuch is tarah se hogi ki ab aapko python ko samajhne me koi dikkat nahi hogi. Is series me hum python ke basics se lekar advance tak ke topics cover karenge. Bht saara behind the scenes bhi seekhne ko milega. Toh chaliye shuru karte hai.
4 |
5 | ## Youtube
6 | series aapko "chai aur code" youtube channel pe milegi.
7 |
8 | ## PR
9 | Please isme koi PR request na kare.
10 |
11 | ## Support
12 | [Discord](https://hitesh.ai/discord)
13 |
14 | ## Whatsapp
15 | [Whatsapp](https://hitesh.ai/whatsapp)
--------------------------------------------------------------------------------