Python Sunday Oct 31
Python Sunday Oct 31
Scratchpad #1
# print(1 + 2) # # Please follow the PEMDAS rule # print((2 + 2) * 2) # hello world sada sadsadsad # # print(100 / 3) current_year = 2021 current_year + 2 print(current_year * 2) next_year = current_year + 1 print(current_year / 2) day_in_a_week = 7 dayInAWeek # camel casing DayInAWeek # pascal # day-in-a-week #
Scratchpad #2
# # score: int = 100 # # score = "hello" # # print(score) # # twitter_handle = None # first_name = "John" # message = "He said, \"this 'is' good\"" # # ['message', '=', 'He said, '] # "You have 5 items in your cart." # first_name = "John" # print(first_name[0]) message = "John Doe is a Python programmer" # message.lower().find("python") message.find("Python").upper()
Scratchpad #3
# 100 - 50 # score = 1 - 10 + 2 # print(score) # print("Hello World") # print("Amount of USD you want to convert?") # usd = input("Amount of USD you want to convert: ") # inr = float(usd) * 74.87 # inr = round(inr, 2) # print(f"${usd} is equal to Rs. {inr}") # age = int(input("Please enter your age: ")) # if age < 18: # print("You are younger than 18") # elif age == 18: # print("You are 18") # elif age == 21: # print("You are 21") # else: # print("You are older than 18") # if age: # print(f"You are {age} years old") # name = input("Please enter your name: ") # if name: # print(f"Hello, {name}") # else: # print("Please enter your name!") # age = int(input("Please enter your age: ")) # if age > 18: # print("You are allowed to enter but not drink") # elif age > 21: # print("You can enter and drink") # elif age > 65: # print("Drinks are free") # else: # print("You are not allowed") # age = int(input("Please enter your age: ")) # if age >= 18 and age < 21: # print("You are allowed to enter but not drink") # elif age >= 21 and age < 65: # else if # print("You can enter and drink") # elif age > 65: # print("Drinks are free") # else: # print("You are not allowed") # if age >= 18 and age < 21: # print("You are allowed to enter but not drink") # if age >= 21 and age < 65: # else if # print("You can enter and drink") # if age > 65: # print("Drinks are free") # else: # print("You are not allowed") # age = int(input("Please enter your age: ")) # if age > 18: # if age > 65: # print("Drinks are free") # elif age > 21: # print("You can enter and drink") # else: # print("You are allowed to enter but not drink") # else: # print("You are not allowed") # if age > 18: # print("You are allowed to enter but not drink") # elif age > 21: # print("You can enter and drink") # elif age > 65: # print("Drinks are free") # else: # print("You are not allowed") # player1 = input("Please enter player 1 choice: ") # player2 = input("Please enter player 2 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 tie") # else: # print("Something went wrong") # for num in range(1000000): # print(f"{num} - Hello World") # for char in "hello world": # print(char) # for num in range(100, 201): # print(num) # for num in range(15): # print(num) # for num in range(1, 5): # print(num) # for num in range(0, 21, 5): # print(num) # for num in range(10, -10, -2): # print(num) 8097297331
Scratchpad #4
# # for num in range(0, 10): # # print(num) # # print("Hello World") # # for num in range(50, 100): # # print(num) # # for num in range(0, 51, 5): # # print(num) # # for num in range(50, 0, 5): # # 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 == 1: # # print(f"{num}: Fizz is odd") # # password = input("Please enter your password: ") # # num = 0 # # while password != "john123": # # print(f"{num}: Wrong password") # # num += 1 # # password = input("Please enter again: ") # # for num in range(0, 10): # # print(num) # # num = 0 # # while num < 100: # # print(num) # # num = num + 1 # # from random import randint # # random_num = randint(1, 10) # # password = input("Please enter your password: ") # # while password != "john123": # # if password == "exit": # # break # # print("Wrong password") # # password = input("Please enter again: ") # # password = input("Please enter your password: ") # # while True: # # if password == "john123": # # break # # print("Wrong password") # # password = input("Please enter again: ") # # ksnd # # john # # while password != "john123": # # print("Wrong password") # # password = input("Please enter again: ") # # count = 0 # # password = input("Please enter your password: ") # # while count < 2: # # if password == "john123": # # break # # print("Wrong password") # # password = input("Please enter again: ") # # count += 1 # from random import randint # random_num = randint(1, 10) # 6 # while True: # guess = int(input("Pick a number between 1 and 10: ")) # 5 # if guess < random_num: # print("Too low") # elif guess > random_num: # print("Too high") # else: # print("Correct!") # print(guess) # play_again = input("Do you want to play again (y/n): ") # if play_again == "y": # random_num = randint(1, 10) # else: # print("Thank you for playing") # break # tasks = "pay bills,practice python,other task" tasks = ["pay bills", "practice python", "other task"]
Scratchpad #5
# # tasks = ["pay bills", "practice python", "other task"] # # print(tasks) # # for task in tasks: # # print(task) # # tasks = ["pay bills", "practice python", "other task"] # # i = 0 # # while i < len(tasks): # # print(tasks[i]) # # i += 1 # # langs = ["Python", "JavaScript", "Rust", "Elm", "WASM"] # # for lang in langs: # # print(lang.upper()) # # i = 0 # # while i < len(langs): # # print(f"{i + 1}: {langs[i]}") # # i += 1 # # i = 1 # # for lang in langs: # # print(f"{i}: {lang}") # # i += 1 # tasks = [] # while True: # task = input("Add task to list (q to quit): ") # if task == "": # print("Please enter a valid task.") # elif task == "q": # break # else: # tasks.append(task) # print(f"You have {len(tasks)} tasks to complete:") # for task in tasks: # print(task) # langs = ["Python", "JavaScript", "Rust", "Elm", "WASM", "Lua"] # print(langs.pop()) # deleted_item = langs.pop() # print(langs) # print(deleted_item) # nums = [1, 4, 3, 7, 9] # squared = [] # for num in nums: # squared.append(num ** 2) # print(squared) # nums = [1, 4, 3, 7, 9] # cubed = [num ** 3 for num in nums] # print(cubed) # nums = [1, 4, 3, 2, 24, 9, 12, 13, 15, 18] # squared = [LOGIC for num in nums if COND] # squared = [num ** 2 for num in nums if num % 2 == 0] # print(squared) # new_nums = [LOGIC if COND else LOGIC for num in nums] # new_nums = [num ** 2 if num % 2 == 0 else num ** 3 for num in nums] # print(new_nums) nums = [[1, 2, 3, 4, 5], [4, 5, 6], [7, 8, 9]] # for lst in nums: # for num in lst: # print(num) # new_nums = [] # for lst in nums: # squared = [] # for num in lst: # squared.append(num ** 2) # new_nums.append(squared) # new_nums = [[num ** 2 for num in lst] for lst in nums] # new_nums = [ # [num ** 2 if num % 2 == 0 else num ** 3 for num in lst] # if len(lst) > 3 # else [num ** 4 if num % 2 == 0 else num ** 5 for num in lst] # for lst in nums # ][:: [num ** 2 for num in nums[0]][1]][0][-1] # print(new_nums)
Scratchpad #6
# product1 = ["iPhone 13", "Apple", 100000, 80, "Some description/info"] # product2 = ["Apple", "iPhone 13", 80, 100000, "Some description/info"] # print(product1[0]) # print(product2[1]) # product3 = { # "name": "iPhone 13", # "description": "Some description and details", # "price": 100000, # "brand": "Apple", # "stock": 80, # "features": ["camera", "microphone"], # "info": {"creator": "Steve Job", "address": "Mountain View"}, # } # product4 = { # 0: "iPhone 13", # 1: "Some description and details", # 2: "Apple", # 3: 100000, # 4: 80, # } # # print(product3["name"]) # # print(product3["description"]) # print(product4[0]) # profile = {"first_name": "John", "last_name": "Doe", "age": 25} # profile2 = dict(first_name="John", last_name="Doe", age=25) # print(profile, profile2) # print(profile["first_name"]) # print(profile["profession"]) # print(profile) # profile["profession"] = "Python Dev" # profile["age"] = 30 # print(profile) # profile = {"first_name": "John", "last_name": "Doe", "age": 25} # print(profile["first_name"]) # ["John", "Doe", 25] # ["first_name", "last_name", "age"] # for item in profile.values(): # print(item) # for item in profile.keys(): # print(item, profile[item]) # for item in profile.items(): # print(item[0], item[1]) # for key, value in profile.items(): # print(key, value) # for k, v in profile.items(): # print(k, v) # song = { # "name": "Parabola", # "artist": "Tool", # "album": "Lateralus", # "released": 2001, # "genres": ["Progressive/Art Rock", "Progressive metal"], # } # for item in song: # print(item) # names = ["john", "jane", "jack", "james"] # upper_names = [item.upper() for item in names] # print(upper_names) # song = { # "name": "Parabola", # "artist": "Tool", # "album": "Lateralus", # "released": 2001, # } # song_mod = {item.upper(): song[item] for item in song} # print(song_mod) # nums = [1, 2, 3, 4, 5] # nums_new = {num: "hello" for num in nums} # print(nums_new) # print({num: num ** 4 for num in range(50)}) # song = { # "name": "Parabola", # "artist": "Tool", # "album": "Lateralus", # } # song2 = {k.upper(): v.lower() for k, v in song.items()} # print(song2) locations = { (1.2132141234, 0.213123): "Mumbai Office", (0.123213213, 1.213123213): "Pune Office", } airports = (("BOM", "Mumbai"), ("MAA", "Chennai"), ("DEL", "Delhi"))
Scratchpad #7
# print("100") # def greet(): # print("Hello World") # print("Hello World") # print("Hello World") # print("Hello World") # print("Hello World") # print("Hello World") # greet() # print(greet) # def square_of_10(): # return "hello world" # result = 10 * 10 # # return result # print(square_of_10()) # print(square_of_10()) # score = 10000 # print(print(square_of_10())) # some_num = square_of_10() # print(some_num) # def square(num): # return num * num # print(square(12)) # print(square(4)) # def greet(name, message): # return f"{message}, {name}" # name = input("Enter your name: ") # message = input("Enter a message: ") # print(greet(name, message)) # print(greet("James", "Hi")) # def square(num): # return num * num # def cube(num): # return square(num) * square(num) # def do_something(a, b): # return cube(a) + cube(b) # print(do_something(4, 5)) # import random # def flip_coin(): # if random.random() > 0.5: # return "HEADS" # else: # return "TAILS" # print(flip_coin()) # def add(a, b): # return a + b # def sub(a, b): # return a - b # def math(a, b, fn): # return fn(a, b) # # print(add(10, 5)) # # print(sub(10, 5)) # print(math(10, 5, sub)) # def sum_odd_numbers(numbers): # total = 0 # for num in numbers: # if num % 2 != 0: # total += num # return total # print(sum_odd_numbers([1, 2, 3, 4, 5])) # def is_odd_number(number): # if number % 2 != 0: # return "ODD" # return "EVEN" # print(is_odd_number(9)) # print(is_odd_number(4)) # def mul(a=1, b=1): # return a * b # print(mul()) def print_name(first_name, last_name="smith"): print(f"My name is {first_name} {last_name}") print_name(first_name="john") # [email protected]
Scratchpad #8
# # name = "John Doe" # # name = "Jack Smith" # # age = 25 # # def greet(): # # def say_hello(): # # movie = "Spiderman - no way home." # # print(name, age, movie) # # say_hello() # # print(name, age) # name = "Jack Smith" # age = 25 # def greet(): # global age # age += 1 # print(f"{name} is {age} years old.") # # def greet(age): # # age += 1 # # print(f"{name} is {age} years old.") # # greet(age) # # greet(age) # # greet(50) # # greet(age) # # print(age) # def outer(): # count = 0 # def inner(): # nonlocal count # count += 1 # print(count) # inner() # outer() from random import choice # Generate random password # count -> int # def gen_password(count): # """Generate a random password that contains # upper and lowercase chars, numbers and special chars # @params # count: int # @return -> str # """ # password = "" # lower_alpha = "abcdefghijklmnopqrstuvwxyz" # nums = "0123456789" # symbols = "!@#$%^&*()" # vals = lower_alpha + lower_alpha.upper() + nums + symbols # while len(password) < count: # password += choice(vals) # return password # print(gen_password(8)) # print(gen_password.__doc__) # print(help(gen_password)) # def add(*nums): # result = 0 # for num in nums: # result += num # return result # print(add(10, 5, 10, 5, 40, 5)) # def profile(**kwargs): # for k, v in kwargs.items(): # print(k, v) # profile(name="John Doe", age=25, profession="Programmer") # def show_info(a, b, *args, role="admin", **kwargs): # print(a) # print(b) # print(args) # print(role) # print(kwargs) # show_info(10, 23, 14, 15, 16, role="moderator", hello="world", info=True) # def add(*nums): # result = 0 # for num in nums: # result += num # return result # nums = [10, 23, 14, 15, 16] # print(add(*nums, 25, 25)) # # print(add(nums, 10)) # def greet(first_name, last_name): # print(f"My name is {first_name} {last_name}.") # profile = {"first_name": "John", "last_name": "Doe"} # greet(**profile) # # greet(first_name="John", last_name="Doe") # def math(a, b, fn): # return fn(a, b) # print(math(10, 4, lambda a, b: a + b)) # print(math(10, 4, lambda a, b: a - b)) # print(math(10, 4, lambda a, b: a * b)) # def add(a, b): # return a + b # def sub(a, b): # return a - b # def div(a, b): # return a / b # test = lambda a, b: a / b # math(10, 5, sub) # print(test(10, 2)) # names = ["john", "jane", "jack", "james"] # upper_cased1 = [name.upper() for name in names] # def uppercase(name): # return name.upper() # upper_cased2 = map(uppercase, names) # upper_cased2 = map(lambda name: name.upper(), names) # print(upper_cased1) # print(list(upper_cased2)) # nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] # evens1 = [num for num in nums if num % 2 == 0] # print(evens1) # evens2 = filter(lambda num: num % 2 == 0, nums) # print(list(evens2)) # names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"] # # less_than_5_chars = filter(lambda name: len(name) < 5, names) # uppercased = map(lambda name: name.upper(), filter(lambda name: len(name) < 5, names)) # # uppercased = [name.upper() for name in names if len(name) < 5] # # print(list(less_than_5_chars)) # print(list(uppercased)) # nums = [12, 23, 435, 2, 323, 3, 34, -234, 0] # print(all(nums)) people = ["John", "Jack", "James", "Jason", "Bane", "Jacob"] print(all(people))
Scratchpad #9
# my_list = [{"name": "John"}, {}, {"name": "Jack"}] # # print(all(my_list)) # if all(my_list): # for item in my_list: # print(item["name"]) # else: # print("Data not good") # people = ["John", "Jack", "James", "Jason", "Brad", "Jane", "Jacob"] # print(any([name[0] == "J" for name in people])) # def colorize(text, color): # colors = ("red", "yellow", "green", "blue", "white", "black") # if type(text) is not str: # raise TypeError("Incorrect Type") # if type(color) is not str: # raise TypeError("Incorrect Type") # if color not in colors: # raise ValueError("Color is not supported") # print(f"{text} in {color}") # colorize(10, "purple") # def divide(a, b): # try: # print(a / b) # except (ZeroDivisionError, TypeError): # print("Something went wrong") # # except TypeError: # # print("Can't divide strings") # def divide(a, b): # try: # print(a / b) # except Exception as err: # print(err) def divide(a, b): try: result = a / b except Exception as err: print(err) else: print(result) finally: print("THIS FUNCTION RAN") divide(10, 0)
Scratchpad #10
# # def login(user, password): # # if password == user["passwd"]: # # print("Welcome") # # else: # # print("Incorrect password") # # login(john, "test@123") # # login(jane, "test") # def user(first_name, last_name, email, phone, passwd): # return { # "first_name": first_name, # "last_name": last_name, # "email": email, # "phone": phone, # "passwd": passwd, # "login": lambda user, passwd: print("welcome") # if passwd == user["passwd"] # else print("Incorrect"), # } # john = user("John", "Doe", "[email protected]", 9210983213, "test") # jane = user("Jane", "Doe", "[email protected]", 9210983213, "test") # # print(john["last_name"]) # john["login"](john, "test@123") # # print(john["last_name"]) # # --------------------------- # class User: # def __init__(self, first_name, last_name, birth_year, email, phone, passwd): # self.first_name = first_name # self.last_name = last_name # self.email = email # self.phone = phone # self.passwd = passwd # self.age = 2021 - birth_year # def login(self, passwd): # if passwd == self.passwd: # print("Welcome") # else: # print("Incorrect Password") # def upload_picture(self, url): # pass # james = User("James", "Smith", "[email protected]", 214324324, "test123") # print(james.first_name) # # print(james.last_name) # james.login("test") # print(james) # james.upload_picture() # class Vehicle: # def __init__(self, make, model, year): # self.make = make # self.model = model # self.year = year # self.country = "India" # ford = Vehicle("Ford", "Mustang", 2020) # suzuki = Vehicle("Maruti", "Wagon R", 2021) # print(ford.model) # print(suzuki.model) # print(ford.country) # print(suzuki.country) class User: def __init__(self, first_name, last_name, dob): self.first_name = first_name self.last_name = last_name self.__dob = dob def get_age(self): age = 2022 - int(self.__dob.split("/")[-1]) return age def get_dob(self): return self.__dob user1 = User("John", "Doe", "12/3/2000") user2 = User("John", "Doe", "13/4/2001") jane = User("Jane", "Doe", "14/5/2002") jane.get_dob() # print(user1.first_name) # print(user2.first_name) # user2.get_age() jane.get_age() # print(user1._User__dob) # print(user1.get_age()) # print(user1.first_name) # print(user1.last_name) # print(user1.dob)
Scratchpad #11
# class User: # total_users = 0 # active = 0 # def __init__(self, first_name, last_name, age): # self.first_name = first_name # self.last_name = last_name # self.age = age # User.total_users += 1 # def __str__(self): # return f"{self.first_name} {self.last_name}" # @classmethod # def get_total_users(cls): # print(f"Total Users: {cls.total_users}") # def info(self): # print(f"My name is {self.first_name} {self.last_name}") # def login(self): # User.active += 1 # print(f"{self.first_name} has logged in.") # def logout(self): # User.active -= 1 # print(f"{self.first_name} has logged out.") # user1 = User("John", "Doe", 20) # user2 = User("Jane", "Doe", 25) # print(user1) # print(user2) # user1.login() # user2.login() # user1.logout() # user1.info() # user2.info() # print(user1.active) # print(user2.active) # print(User.active) # User.get_total_users() # user1.get_total_users() # class Math: # @classmethod # def add(cls, a, b): # return a + b # @classmethod # def sub(cls, a, b): # return a - b # @classmethod # def mul(cls, a, b): # return a * b # print(Math.add(10, 2)) # print(Math.sub(10, 2)) # # BASE CLASS # class User: # def __init__(self, first_name, last_name, age): # self.first_name = first_name # self.last_name = last_name # self.age = age # def __str__(self): # return f"{self.first_name} {self.last_name}" # def info(self): # print(f"My name is {self.first_name} {self.last_name}") # def login(self): # print(f"{self.first_name} has logged in.") # def logout(self): # print(f"{self.first_name} has logged out.") # # SUB CLASS # class Moderator(User): # def login(self): # print(f"A mod has logged in") # print(f"{self.first_name} has logged in.") # def create_group(self, group_name): # print(f"{group_name} has been created.") # john = User("John", "Doe", 25) # jack = Moderator("Jack", "Smith", 20) # john.login() # jack.login() # jack.create_group("Python") # class User: # def __init__(self, name, email, password): # self.first_name = name # self.email = email # self._password = User.validate_password(password) # @classmethod # def validate_password(cls, password): # pass # def get_password(self): # print(self._password) # def set_password(self, new_password): # if len(new_password) < 8: # raise ValueError("Password has to above 8 characters") # if new_password.find(" ") > 0: # raise ValueError("Password cannot contain spaces") # self._password = new_password # @property # def password(self): # return self._password # @password.setter # def password(self, new_password): # if len(new_password) < 8: # raise ValueError("Password has to above 8 characters") # if new_password.find(" ") > 0: # raise ValueError("Password cannot contain spaces") # self._password = new_password # user1 = User("John Doe", "[email protected]", "12345") # user1.get_password() # user1.set_password("helloworld") # print(user1.password) # try: # user1.password = "Hello World" # except Exception as err: # print(err) # class User: # def __init__(self, name, email): # self.name = name # self.email = email # def info(self): # return f"{self.name} - {self.email}" # class Moderator(User): # def __init__(self, name, email, password): # super().__init__(name, email) # self.password = password # user1 = User("John Doe", "[email protected]") # user2 = Moderator("Jane Doe", "[email protected]", "1234") # print(user2.password) # class Human: # def __init__(self, name): # self.name = name # def talk(self): # print("Hello, how are you?") # def think(self): # print(f"{self.name} is thinking") # class Animal: # def __init__(self, name): # self.name = name # def talk(self): # print("KAMSKJDNASLKJDNAKJDSLKJDSAN") # def run(self): # print(f"{self.name} is running") # class Mutant(Animal, Human): # def talk(self): # print("ARRRRRRRRRRRRR") # wolverine = Mutant("Logan") # # wolverine.run() # # wolverine.think() # # wolverine.talk() # print(help(Mutant)) # print(len("hello")) # print(len([1, 2, 3, 4, 5, 6, 7, 8])) # print(10 + 10) # print("10" + "10") # class Human: # def __init__(self, name, age): # self.name = name # self.age = age # def __str__(self): # return self.name # def info(self): # return f"{self.name} is {self.age} years old." # def __len__(self): # return self.age # def __add__(self, another_human): # if isinstance(another_human, Human): # return Human("New Born", 0) # else: # raise Exception("This is sick!") # class Animal: # pass # tom = Animal() # john = Human("John Doe", 20) # jane = Human("Jane Doe", 21) # print(len(john)) # print(john + jane) # def my_for(iterable): # iterator = iter(iterable) # while True: # try: # print(next(iterator)) # except StopIteration: # break # def my_map(func, iterable): # iterator = iter(iterable) # while True: # try: # func(next(iterator)) # except StopIteration: # break # # my_for([1, 34, 23, 14, 5]) # my_map(lambda num: print(num * num), [1, 2, 3, 4]) 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 c = Counter(0, 100, 5) r = range(0, 10) for num in c: print(num)
Scratchpad #12
# def count_to(max): # count = 1 # while count <= max: # yield count # count += 1 # counter = count_to(5) # print(next(counter)) # print(next(counter)) # print(next(counter)) # print(next(counter)) # print(next(counter)) # print(next(counter)) # print(next(counter)) # print(next(counter)) # def fib_list(max): # nums = [] # a, b = 0, 1 # while len(nums) < max: # nums.append(b) # a, b = b, a + b # return nums # # print(fib_list(100000)) # def fib_gen(max): # a, b = 0, 1 # count = 0 # while count < max: # a, b = b, a + b # yield a # count += 1 # for num in fib_gen(100000): # print(num) # from time import time # # list_start_time = time() # # print(sum([num for num in range(1000000000)])) # # list_end_time = time() - list_start_time # gen_start_time = time() # print(sum(num for num in range(1000000000000000000))) # gen_end_time = time() - gen_start_time # # print(f"List comp took {list_end_time}") # print(f"Gen Exp took {gen_end_time}") # def math(a, b, fn): # def random_num(): # return 5 # return fn(a, random_num()) # print(math(10, 5, lambda a, b: a - b)) # # Higher order function # def sum(n, func): # total = 0 # for num in range(1, n + 1): # total += func(num) # return total # # callback function # def square(n): # return n * n # # callback function # def cube(n): # return n * n * n # print(sum(10, cube)) # callback # import random # # Higher order function # 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")) # # print(greet("John")) # # print(greet("John")) # # print(greet("John")) # import random # # Function factory # 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 # greet_john = make_greet_func("John") # greet_jane = make_greet_func("Jane") # print(greet_john()) # print(greet_jane()) # def stars(fn): # def wrapper(): # print("*" * 10) # fn() # print("*" * 10) # return wrapper # @stars # say_hello = stars(say_hello) # def say_hello(): # print("Hello World") # # @classmethod # test = classmethod(test) # # def test(): # # pass # say_hello() def stars(fn): """Will add 10 stars to the top and bottom""" def wrapper(*args, **kwargs): """Internal wrapper function. This is what you will actually use """ print("*" * 10) fn(*args, **kwargs) print("*" * 10) return wrapper @stars def say_hello(name): """Will say hello to whoever""" print(f"Hello, {name}") @stars def say_hello2(name, message): """Will say whatever to whoever""" print(f"{message}, {name}") print(say_hello2.__doc__)
Scratchpad #13
# # from functools import wraps # def stars(fn): # """Will add 10 stars to the top and bottom""" # @wraps(fn) # def wrapper(*args, **kwargs): # """ # Internal wrapper function. This is what you will actually use # """ # print("*" * 10) # fn(*args, **kwargs) # print("*" * 10) # return wrapper # @stars # def say_hello(name): # """Will say hello to whoever""" # print(f"Hello, {name}") # @stars # def say_hello2(name, message): # """Will say whatever to whoever""" # print(f"{message}, {name}") # print(say_hello.__doc__) # @decorator("hello") # def func(): # pass # func = decorator(func) # from functools import wraps # def ensure_first_arg(val): # def inner(fn): # def wrapper(*args, **kwargs): # if args and args[0] != val: # print(f"First arg should be {val}") # else: # return fn(*args, **kwargs) # return wrapper # return inner # @ensure_first_arg("inception") # def fav_movies(*movies): # print(movies) # # fav_movies = ensure_first_arg("inception")(fav_movies) # fav_movies("inception", "blood diamond", "shutter island", "the beach") # def enforce(*types): # (str, int) # def inner(fn): # announce # def wrapper(*args, **kwargs): # (10, 10) # new_args = [] # for a, t in zip(args, types): # [(10, str), (10, int)] # print(a, t) # try: # new_args.append(t(a)) # int(10) # except (ValueError, TypeError) as e: # return "Something went wrong" # return fn(*new_args) # return wrapper # return inner # # @enforce(str, int)(annouce) # @enforce(str, int) # def announce(msg, times): # print((msg + "\n") * times) # announce(10, "pachas") # from pprint import pprint # users = [ # {"name": "John Doe", "age": 19, "phone": 12345}, # {"name": "John Doe", "age": 19, "phone": 12345}, # {"name": "John Doe", "age": 19, "phone": 12345}, # {"name": "John Doe", "age": 19, "phone": 12345}, # ] # pprint(users) # import random # from random import randint # print(randint(10, 100)) # import random from random import randint as rai, choice as ch # import random as r # from random import * print(rai(0, 10)) print(ch(["hello", "world", "universe"]))
Scratchpad #14
# file = open("test.txt") # print(file.read()) # file.close() # file = open("test.txt") # with open("test.txt", "r") as file: # print(file.read()) # print(file.closed) # print(file.closed) # with open("test.txt", "w") as f: # f.write("Hello World\n") # f.write("Hello Galaxy\n") # f.write("Hello Universe\n") # with open("test.txt", "w") as file: # file.write("Hello" * 100) # with open("test.txt", "a") as file: # file.write("\n\nThis is some additional text\n") # with open("test.txt", "r+") as file: # file.write("NAMESTE \nPYTHON") # # file.seek(40) # # file.write("THIS IS A PYTHON IO OPERATION") # message = "Hello World\nThis is another line\nThis is one more line\nHello Universe\nHello Pythom" # message = """Hello World # This is another line # This is one more line # Hello Universe # Hello Python""" # print(message) # with open("test.txt", "r") as file: # data = file.read() # data = data.replace("Hello", "Namaste") # with open("test.txt", "w") as file: # file.write(data) ### TASKS # 1. search_and_replace(file, search_term, replace_term) # 2. get_stats(file) # return {"words": 100, "chars": 100, "lines": 100} # 3. duplicate_file(file, new_name) # 4. read_csv -> iterator object # 5. random_int(max) -> int # with open("test.csv") as file: # data = file.readlines() # filtered_data = [] # final_data = [] # for row in data: # filtered_data.append(row.replace("\n", "")) # for row in filtered_data: # final_data.append(row.split(",")) # print(final_data) from csv import reader, DictReader, writer, DictWriter # with open("test.csv") as file: # data = reader(file) # # print(list(data)) # next(data) # for row in data: # print(row) # with open("test.csv") as file: # # data = DictReader(file, delimiter="|") # data = DictReader(file) # # print(list(data)) # total = 0 # for row in data: # total += int(row["phone"]) # print(total) # with open("marvel_movies.csv", "w") as file: # csv_writer = writer(file) # csv_writer.writerow(["name", "rating"]) # csv_writer.writerow(["Spider man - No way home", 1.5]) # csv_writer.writerow(["Doctor Strange", 1.3]) # csv_writer.writerow(["Desh Drohi", 5]) # with open("marvel_movies.csv", "w") as file: # headers = ["name", "rating"] # csv_writer = DictWriter(file, fieldnames=headers) # csv_writer.writeheader() # csv_writer.writerow({"name": "Thor", "rating": 3}) # csv_writer.writerow({"name": "Suryavanshi", "rating": 1}) # csv_writer.writerow({"name": "Pushpa", "rating": 3.4}) # with open("governors_county.csv") as file: # data = reader(file) # total_votes = 0 # with open("indiana_county.csv", "w") as file: # csv_writer = writer(file) # for row in data: # if row[0] == "Indiana": # csv_writer.writerow(row) # for row in data: # if row[0] == "Indiana": # # print(row[0], row[3]) # total_votes += int(row[3]) # print(total_votes) # with open("governors_county.csv") as file: # data = reader(file) # total_votes = 0 # with open("indiana_county.csv", "w") as file: # csv_writer = writer(file) # csv_writer.writerow( # ["state", "county", "current_votes", "total_votes", "percent"] # ) # for row in data: # if row[0] == "Indiana": # csv_writer.writerow(row) import pickle class User: def __init__(self, name, age): self.name = name self.age = age def introduce(self): print(f"My name is {self.name} and I am {self.age} years old") user1 = User("John Doe", 20) user2 = User("Jane Doe", 25) # user1.introduce() # user2.introduce() # with open("users.pickle", "wb") as file: # pickle.dump((user1, user2), file) with open("users.pickle", "rb") as file: user1, user2 = pickle.load(file) # print(user1) user1.introduce() user2.introduce()
Scratchpad #15
# import json # import jsonpickle # class User: # def __init__(self, name, age): # self.name = name # self.age = age # def introduce(self): # print(f"My name is {self.name} and I am {self.age} years old") # user1 = User("John Doe", 20) # user2 = User("Jane Doe", 25) # # print(json.dumps(user1.__dict__)) # # jsontest = jsonpickle.encode((user1, user2)) # # print(jsontest) # with open("data.json", "w") as file: # stored = jsonpickle.encode((user1, user2)) # file.write(stored) # # with open("data.json") as file: # # contents = file.read() # # restored = jsonpickle.decode(contents) # # print(restored) # # restored.introduce() import re # pattern = re.compile(r"\d{3}\s\d{4}-?\d{4}") # text = "Call us on 022 2334-2323 or 022 12341234" # # result = pattern.search(text) # result = pattern.findall(text) # # print(result.group()) # print(result) # def validate_phone(num): # """Validates a phone number. ex. pattern - 022 2312 2133""" # # pattern = re.compile(r"^\d{3}\s\d{4}-?\d{4}$") # pattern = re.compile(r"\d{3}\s\d{4}-?\d{4}") # match = pattern.fullmatch(num) # if match: # return True # else: # return False # validate_phone() # # print(validate_phone("Call us on 022 2334-2323 or 022 12341234")) # print(validate_phone("022 2334-2323")) # TASK ################## Bank # name: str # initial: str # address: str # phone_nos: str[] # total_customers: Customer[] # total_balance: float # customers_count: int # get_bank_info() -> {name: str, initial: str, address: str, phone_nos: str[], customers_count: int} # get_customers_list() -> Customer[] # find_customer_by_acc_no(acc_no) -> Customer # find_customers_by_name(name) -> Customer[] # export_customers_as_csv(path) -> void # export_customers_as_json(path) -> void # add_new_customer() -> Customer # // new_cust = Customer("frst", "doe", bank=self) # // total_customers.append(new_cust) # // customers_count += 1 # // return new_cust # __repr__() / __str__() ################## Customer # first_name: str # last_name: str # dob: str // @requires_validation YYYY-mm-dd # phone_no: str # address: str # aadhaar_card_no: str // @requires_validation # pan_card_no: str // @requires_validation # nominee_list: {name: str, phone: str, address:str, dob: str}[] # account_no // generated using gen_acc_no() # balance: float // default 0 # bank: Bank # __repr__() / __str__() # deposit(amt: float) -> float # // print - "Previous balance: Rs. {}, Current balance: Rs. {}" # withdraw(amt: float) -> float # // print - "Previous balance: Rs. {}, Current balance: Rs. {}" # // check balance then return or else raise exception # get_info() -> dict # get_balance() -> float # change_name(new_fist_name: str, new_last_name: str) -> bool # change_phone_no(new_no: str) -> bool # change_address(new_address: str) -> bool ###################### helpers.py # def gen_acc_no(initials, no_count) -> str // sbi-8888888800 # -------------------------------------------------------- # from helpers import gen_acc_no # class Customer: # def __init__(self, bank_initials, first_name, last_name, ....): # self.first_name = first_name # self.last_name = last_name # self.account_no = gen_acc_no(bank_inital, 10) # sbi = Bank(...) # john = sbi.add_new_customer(...) # please check all arguments # raise exceptions # all functions should have docstring # Customer.py # Bank.py # helpers.py
Scratchpad #16
# import sqlite3 # data = ("john", "doe", 25) # data_list = [("jack", "smith", 35), ("jane", "doe", 33), ("jill", "mehta", 45)] # conn = sqlite3.connect("bank.db") # c = conn.cursor() # # c.execute("CREATE TABLE customers (first_name TEXT, last_name TEXT, age INTEGER);") # # c.execute("INSERT INTO customers VALUES ('salman', 'khan', 52);") # query = """INSERT INTO customers VALUES (?, ?, ?);""" # # c.execute(query, data) # # c.executemany(query, data_list) # for row in data_list: # print(f"Writing {row[0]} to database...") # c.execute(query, row) # conn.commit() # conn.close() # from pymongo import MongoClient # client = MongoClient("mongodb://127.0.0.1:27017") # db = client.bankapp2 # coll = db["customers"] # doc = {"firstName": "John", "lastName": "Doe", "age": 25} # docs = [ # {"firstName": "Jack", "lastName": "Smith", "age": 34}, # {"firstName": "Jill", "lastName": "Mehta", "age": 43}, # {"firstName": "Jane", "lastName": "Webb", "age": 21}, # ] # coll.insert_one(doc) # coll.insert_many(docs) # query = {"age": {"$gt": 30}} # search_res = coll.find(query) # for res in search_res: # print(res) # # print(list(search_res)) # coll.delete_many({"age": {"$gt": 30}}) # client.drop_database("bankapp2") # from selenium import webdriver # from selenium.webdriver.common.keys import Keys # from time import sleep # browser = webdriver.Chrome( # r"/home/rahul/Desktop/Class/Python/oct_31_2021_sundays/scratchpads/chromedriver" # ) # browser.maximize_window() # browser.get("https://www.youtube.com/") # sleep(3) # search_box = browser.find_element_by_xpath( # "/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div[1]/div[1]/input" # ) # search_box.click() # sleep(1) # search_box.send_keys("batman movie trailer", Keys.ENTER) # sleep(30) # video = browser.find_element_by_partial_link_text("THE BATMAN") # sleep(1) # video.click() # sleep(30) # browser.get() # browser.close() from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep browser = webdriver.Chrome( r"/home/rahul/Desktop/Class/Python/oct_31_2021_sundays/scratchpads/chromedriver" ) browser.maximize_window() browser.get("https://web.whatsapp.com") sleep(15) search_box = browser.find_element_by_xpath( "/html/body/div[1]/div[1]/div[1]/div[3]/div/div[1]/div/label/div/div[2]" ) sleep(1) search_box.click() sleep(2) search_box.send_keys("PYTHON SUN RS 24", Keys.ENTER) sleep(2) msg_box = browser.find_element_by_xpath( "/html/body/div[1]/div[1]/div[1]/div[4]/div[1]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[2]" ) sleep(1) msg_box.click() sleep(2) for i in range(20): msg_box.send_keys(f"SPAM MESSAGE {i + 1}", Keys.ENTER) sleep(20) browser.close() # class Bank: # def __init__(self): # self.total_customers = [] # def create_customer(self): # cus = Customer() # self.total_customers.append(cus) # return # sbi = Bank("") # sbi.create_customer("Asdnakjsdnkjsad")