Python Evening 27-06-2022
Python Evening 27-06-2022
Scratchpad #1
score = 10 score + 5 high_score = score * 2 print(high_score)
Scratchpad #3
# print("Amount of US dollars you want to convert?") # usd = input() # usd = input("Amount of US dollars you want to convert? ") # inr = float(usd) * 78 # print(f"${usd} is equal to Rs. {inr}") # print(input("Hello World ")) # print(int(input("Amount of US dollars you want to convert? ")) * str(10)) # city = input("Which city do you live in? ") # if city == "delhi": # print("You are not allowed anywhere") # elif city == "mumbai": # print("Please come") # elif city == "pune": # print("Good come in") # else: # print("Sure come in") # username = "" # if username: # print("Here is your content") # else: # print("You have to login") # age = 3100 # if age >= 65: # print("You can enter but you cannot drink") # elif age >= 21: # print("You can enter and you can drink") # elif age >= 18: # print("Drink are free") # else: # print("Not allowed") age = 31 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("Drink are free") else: print("Not allowed")
Scratchpad #4
# age = 1 # city = "delhi" # if age > 18: # if city == "delhi": # print("You aren't allowed") # else: # print("You can enter") # else: # print("You are not allowed") # player1 = input("Enter player 1's choice: ") # player2 = input("Enter player 2'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 tie") # else: # print("Something went wrong") # for something in "rstforum": # print(something, "Hello World") # for c in "hello": # print(c) # for item in "some text": # print(item) # print("Hello") # for number in range(50, 100): # print(number) # for num in range(10): # print(num) # for num in range(0, 101, 10): # print(num) # for num in range(1, -100, -10): # print(num) # for num in range(1, 21): # if num == 5 or num == 16: # print(num, "FizzBuzz") # elif num % 2 == 0: # print(num, "Fizz is even") # else: # print(num, "Fizz is odd") password = input("Please enter your password: ") while password != "test": print("Incorrect password") password = input("Please enter your password again: ") print("Welcome")
Scratchpad #5
# password = input("Please enter your password: ") # while password != "test": # print("Incorrect password") # password = input("Please enter your password again: ") # print("Welcome") # for num in range(1, 10): # range, list, string # print(num) # for char in "hello": # print(char, "Hello World") # num = 1 # while num < 10: # print(num) # # num = num + 1 # num += 1 # name = "john doe" # for char in name: # print(char) # count = 0 # while count < len(name): # print(name[count]) # count += 1 # password = input("Please enter your password: ") # while password != "test": # print("Incorrect password") # password = input("Please enter your password again: ") # if password == 'quit': # break # password = input("Please enter your password: ") # while True: # print("Incorrect password") # password = input("Please enter your password again: ") # if password == 'test': # break # for num in range(1, 10): # if num == 5: # break # print(num) # password = input("Please enter your password: ") # while True: # print("Incorrect password") # password = input("Please enter your password again: ") # if password == 'test': # break # while True: # player1 = input("Enter player 1's choice: ") # player2 = input("Enter player 2'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 tie") # else: # print("Something went wrong") # answer = input("Do you want to play again? (y/n) ") # if answer == 'n': # break # tasks = "practice python||pay bills||another task" # name1 = "john" # name2 = "jane" # names = [name1, "jack", name2, 100, "hello world"] # print(names) nums = [1, 2, 5, 20, [1, 2, 3]] # print(nums[4]) print(len(nums))
Scratchpad #6
# nums = list(range(100)) # for n in nums: # print(n) nums = ["jane", "john", "jack", "jill", "jeet"] count = 0 while count < len(nums): print(nums[count]) count += 1
Scratchpad #7
# names = ['tijlad', 'daljit', 'amit', 'sahil', 'sarvesh', 'abhay'] # upper_names = [] # for name in names: # upper_names.append(name.upper()) # print(upper_names) # upper_names2 = [name.upper() for name in names] # print(upper_names2) # >>> [name[1:3] for name in names] # ['ij', 'al', 'mi', 'ah', 'ar', 'bh'] # >>> names # ['tijlad', 'daljit', 'amit', 'sahil', 'sarvesh', 'abhay'] # >>> # >>> # >>> # >>> [name for name in names] # ['tijlad', 'daljit', 'amit', 'sahil', 'sarvesh', 'abhay'] # >>> [name[::-1] for name in names] # ['daljit', 'tijlad', 'tima', 'lihas', 'hsevras', 'yahba'] # >>> # >>> "john"[1:3] # 'oh' # >>> # >>> # >>> # >>> # >>> [10 for name in names] # [10, 10, 10, 10, 10, 10] # >>> [ for name in names] # KeyboardInterrupt # >>> # >>> # >>> # >>> names # ['tijlad', 'daljit', 'amit', 'sahil', 'sarvesh', 'abhay'] # >>> # >>> [len(name) for name in names] # [6, 6, 4, 5, 7, 5] # >>> [len(name) ** 2 for name in names] # [36, 36, 16, 25, 49, 25] # >>> # >>> # >>> # >>> # >>> name # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # NameError: name 'name' is not defined. Did you mean: 'names'? # >>> # >>> names[0] # 'tijlad' # >>> names[0][1:] # 'ijlad' # >>> # >>> names[0][1:4] # 'ijl' # >>> # >>> names[0][::] # 'tijlad' # >>> names[0][::-1] # 'daljit' # >>> names # ['tijlad', 'daljit', 'amit', 'sahil', 'sarvesh', 'abhay'] # >>> # >>> # >>> numbers = [1, 2, 3, 4, 5] # >>> # >>> numbers # [1, 2, 3, 4, 5] # >>> [num * 2 for num in numbers] # [2, 4, 6, 8, 10] # >>> # >>> [num / 2 for num in numbers] # [0.5, 1.0, 1.5, 2.0, 2.5] # >>>
Scratchpad #8
# prod1 = ["iPhone", "Apple", 100000, 500, "Some desc", True] # prod2 = ["Note 7", "Mi", 50000, 15000, "Some desc", False] # print(f"Name: {prod1[0]}\nBrand: {prod1[1]}\nPrice: {prod1[2]}") # print(f"Name: {prod2[0]}\nBrand: {prod2[1]}\nPrice: {prod2[2]}") # nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # print(nums[1][-1]) # [[[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]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]] # nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # for num in nums: # for n in num: # print("inner loop", n) # nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # i = 0 # while i < len(nums): # j = 0 # while j < len(nums[i]): # print(nums[i][j]) # j += 1 # i += 1 nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] total = 0 i = 0 while i < len(nums): j = 0 while j < len(nums[i]): total = total + nums[i][j] j += 1 i += 1 print(total) # i = 0 # while i < len(nums): # print(nums[i]) # i += 1 nums = [ [[1, 2, 3, 4], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3, 73], [1, 32, 3, 45]], [[1, 2, 3], [1], [1, 2, 3]], ] # task 1 = total = ? # task 2 = total = even numbers
Scratchpad #9
# i = 0 # while i < 10: # j = 0 # print("I am here in i") # while j < 10: # print("I am here in j") # print(j) # j += 1 # print(i) # i += 1 # # print("Hello World") # product1 = [ # "iPhone", "Apple", 100000, 100, True, "Some description", "Some other text" # ] # print(product1[1]) # product1 = { # "description": "Some description...", # "price": 100000, # "in_stock": 100, # "name": "iPhone", # "discount_available": True, # "brand": "Apple", # 100: "Something" # } # print(product1["brand"]) # print(product1[100]) # song = { # "name": "saap", # "artist": ["john doe", "jane doe"], # "album": "pythonic", # "track_time": 3.42, # "downloadable": True, # "metadata": { # "youtube_link": "https://....", # "spotify_link": "https://....", # } # } # # print(song["track_time"]) # # print(song["artist"][1]) # print(song) # # print(song["artist"][0]) # # print(song["metadata"]["spotify_link"]) # my_playlist = [ # { # "name": "saap", # "artist": ["john doe", "jane doe"], # "album": "pythonic", # "track_time": 3.42, # "downloadable": True, # "metadata": { # "youtube_link": "https://....", # "spotify_link": "https://....", # } # }, # { # "name": "naag", # "artist": ["john doe", "jane doe"], # "album": "pythonic", # "track_time": 3.42, # "downloadable": True, # "metadata": { # "youtube_link": "https://....", # "spotify_link": "https://....", # } # }, # { # "name": "naagin", # "artist": ["john doe", "jane doe"], # "album": "pythonic", # "track_time": 3.42, # "downloadable": True, # "metadata": { # "youtube_link": "https://....", # "spotify_link": "https://....", # } # }, # ] # profile = {"name": "John", "age": 20} # profile2 = dict(name="John", age=20) # print(profile) # print(profile2) # prod_name = input("Apne product ka naam dal: ") # product = {"name": prod_name} # print(product) # profile = {"name": "John", "age": 20} # print(profile["namee"]) product1 = { "description": "Some description...", "price": 100000, "in_stock": 100, "name": "iPhone", "discount_available": True, } # print(product1["description"]) # for key in product1.keys(): # print(key, product1[key]) # for item in product1.values(): # print(item) # for item in product1.items(): # print(item[0], item[1], item) # for k, v in product1.items(): # print(k, v) song = { "name": "Parabola", "artist": "Tool", "album": "Lateralus", "released": 2001, "genres": ["Progressive/Art Rock", "Progressive metal"], }
Scratchpad #10
profile = {"name": "John Doe", "age": 20, "profession": "Programmer"} print(profile)
Scratchpad #11
# locations = { # "name": "john doe", # 10: "hello", # (1.231423, 0.123123): "Mumbai office", # (1.221223, 0.131453): "Pune office", # } # print(locations["name"]) # print(locations[10]) # print(locations[(1.231423, 0.123123)]) # names = ("Corey", "Maynard", "Morrisey", "Thom") # # for name in names: # # print(name) # count = 0 # while count < len(names): # print(names[count]) # count += 1 # count = count + 1 users1 = {"sahil", "nikhil", "savio", "amit", "onkar", "sherwin", "aayush"} users2 = { "priyanka", "nikhil", "savio", "gokul", "shrushti", "sarthik", "aishwarya", "onkar" } # nums1 = {12, 324, 4562, 23, 12, 1, 23, 45} # nums2 = {12, -1, 3, 23, 234, 1, 23, 45.23} print(users1) print(users2) print("\n\n") print("Union") print(users1 | users2) # union operator # print(nums1 | nums2) print("intersection operator") print(users1 & users2) # intersection operator print("symmetric difference") print(users1 ^ users2) # symmetric difference
Scratchpad #12
# print("Hello World") # # DRY - Don't repeat yourself # # WET # def greet(): # print("Hello World") # print("Hello World") # print("Hello World") # greet() # greet() from random import random # def flip_coin(): # random_num = random() # if random_num > 0.5: # print("HEADS") # else: # print("TAILS") def flip_coin(): random_num = random() if random_num > 0.5: return "HEADS" else: return "TAILS" # print(flip_coin()) # result = flip_coin() # print(f"The result is {result}") # def best_of_3(): # flip_coin() # flip_coin() # flip_coin() # best_of_3() # def greet(name, message): # return f"{message} {name}" # print(greet("Hi", "Jack")) # print(greet("John", "Hello")) # def flip_multiple(times): # for num in range(times): # print(flip_coin()) # user_input = input("Number of times you flip the coin: ") # flip_multiple(int(user_input)) # def add(a, b): # return a + b # result = add(10, 3) # print(f"The result of your calculation was {result}") # def sum_odd_nums(nums): # total = 0 # for num in nums: # if num % 2 != 0: # total += num # return total # print(sum_odd_nums([1, 2, 3, 4, 5])) # def is_odd_num(num): # if num % 2 != 0: # return True # return False # print(is_odd_num(4)) def expo(num=1, power=1): return num**power print(expo())
Scratchpad #13
# user_input = input("Please enter: ") # print(type(user_input)) # print(user_input) # def add(a, b): # return a + b # print(add(10, 4)) # def greet(message="Hi", name="Unknown"): # return f"{message}, {name}" # print(greet(name="John")) # full_name = "john doe" # full_name = "jane doe" # def greet(): # full_name = "Jack Smith" # print(full_name) # print(full_name) # greet() # total = 0 # def test(): # global total # total += 10 # print(total) # test() # total = 0 # def test(val): # return val + 10 # total = test(total) # print(total) # def outer(): # """ # This function does something # """ # count = 100 # def inner(): # nonlocal count # count += 10 # return count # return inner() # print(outer.__doc__) # # print(type.__doc__) # def test(): # total = 0 # for num in range(1, 10): # total += num # return total # print(test()) # def add(*nums): # total = 0 # for num in nums: # total += num # return total # print(add(10, 20, 12)) # def names(**vals): # for k, v in vals.items(): # print(f"{k} - {v}") # names(name="John", age=20, job="programmer", working=False) def show_info(a, b, *args, role="moderator", **kwargs): print(a, b, args, role, kwargs) show_info(10, 20, 30, 40, 50, role="programmer", hello="world", name="john")
Scratchpad #14
# def add(*nums): # total = 0 # for num in nums: # total += num # return total # my_values = [10, 4, 5, 2, 1, 23] # print(add(*my_values)) # def greet(first_name, last_name): # print(f"Hello my name is {first_name} {last_name}") # # info = ["john", "doe"] # # greet(*info) # info = {"first_name": "John", "last_name": "Doe"} # greet(**info) # def add(a, b): # return a + b # add = lambda a, b: a + b # print(add(10, 5)) # def math(a, b, fn1, fn2): # return [fn1(a, b), fn2(a, b)] # print(math(10, 5, sub, add)) # def math(a, b, fn1, fn2): # return fn1(a, b) # # def add(a, b): # # return a + b # # def sub(a, b): # # return a - b # print(math(10, 4.5, lambda a, b: a + b, lambda a, b: a - b)) # print(math(10, 4, lambda a, b: a - b)) # print(math(10, 4, lambda a, b: a * b)) add = lambda a, b: print(a + b) print(add(10, 5))
Scratchpad #15
# def add(a, b): # return a + b # add = lambda a, b: a + b # nums = [1, 2, 3, 4, 5, 6, 7, 8] # # doubles = [num * 2 for num in nums] # # print(doubles) # def num_double(num): # return num * 2 # doubles = map(lambda num: num * 2, nums) # # doubles = map(num_double, nums) # # print(list(doubles)) # print(doubles) # for num in doubles: # print(num) # names = ["john", "john", "jill gupta", "jack gupta", "sarvesh smith"] # uppercased_names = map(lambda name: name.upper(), names) # print(list(uppercased_names)) # for name in uppercased_names: # print(name) # nums = [1, 2, 3, 4, 5, 6, 7, 8] # odds = filter(lambda num: num % 2 != 0, nums) # print(list(odds)) # names = ["ohjn", "john", "jill gupta", "jack gupta", "sarvesh smith"] # result = filter(lambda name: name[0] != 'j', names) # print(list(result)) # products = [ # { # "name": "iPhone", # "brand": "Apple", # "price": 1200 # }, # { # "name": "Nord", # "brand": "One Plus", # "price": 800 # }, # { # "name": "Galaxy S22", # "brand": "Samsung", # "price": 1400 # }, # ] # products = list(filter(lambda product: product["price"] < 1000, products)) # print(products) # # print(products[2]["price"]) # # products = list( # # map( # # lambda product: { # # "name": product["name"], # # "brand": product["brand"], # # "price": product["price"] * 82 # # }, products)) # # print(products) # 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)) # names = [None, False, ' '] # # print(all(names)) # print(any(names)) numbers = {2, 3, 7, 3, 9, 1} print(sorted(numbers))
Scratchpad #16
# print(max(10, 20, 0, -3, 21, 233, 23)) # print(min(10, 20, 0, -3, 21, 233, 23)) # result = reversed("hello") # print("".join(result)) # result = reversed([10, 20, 0, -3, 21, 233, 23]) # print(list(result)) # print(abs(-5)) # print(abs(5)) # print(sum(range(10), 10)) # print(sum([1, 2, 3, 4], 5)) # products = [ # { # "name": "iPhone", # "brand": "Apple", # "price": 1200 # }, # { # "name": "Nord", # "brand": "One Plus", # "price": 800 # }, # { # "name": "Galaxy S22", # "brand": "Samsung", # "price": 1400 # }, # ] # prices = list(map(lambda product: product["price"], products)) # print(sum(prices)) # print(round(10.7898, 2)) # result = zip([1, 2, 3, 4, "hello"], ["john", "jane", 10, 100, "jack", True], # [1, 2]) # print(list(result)) # def my_func: # print("hello world") # print(hello) # def greet(name): # if type(name) != str: # # raise TypeError("Please enter a string value") # raise Exception("Please enter a string value") # return f"Hello, {name}" # print(greet(100)) def contains_john(*names): return "john" in names print(contains_john("jack", "jill")) # rahul@rstforum.co.in
Scratchpad #17
# try: # num = int(input("Please enter a number: ")) # print(num) # except ValueError as err: # print(err) # print("Hello World") # def divide(a, b): # try: # result = a / b # print(result) # except (TypeError, ZeroDivisionError) as err: # print(err) # def divide(a, b): # try: # result = a / b # print(result) # 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("******") # print("I will always run") # print("******") # divide(1, 0) # divide(1, "hello") # divide(1, 3) # print("Hello World") # import random # print(random.random()) # import random as r # random = "Hello World" # print(random) # print(r.random()) # # import random # from random import randint as ri, random as r, choice as ch # # from random import * # print(ri(10, 100)) # print(ch()) # import mymod # print(mymod.add(10, 5)) from mymod import sub print(sub(10, 5))
Scratchpad #18
# nums = [1, 2, 3, 4, 5] # def list_manipulation(data, command, location, value=0): # # logic # list_manipulation(nums, "remove", "end") # 5 # list_manipulation(nums, "remove", "beginning") # 1 # list_manipulation(nums, "add", "beginning", 100) # [100, 2, 3, 4] # list_manipulation(nums, "add", "end", 100) # [100, 2, 3, 4, 100] # print(nums) # [1,2,3,4] # print(nums) # [2,3,4]
Scratchpad #19
# from unicodedata import name # "john".upper() # class User: # # constructor # def __init__(self, fn, ln, a): # self.first_name = fn # self.last_name = ln # self.age = a # user1 = User("john", "doe", 20) # user2 = User("jane", "smith", 30) # print(user1.first_name) # print(user2.first_name) class Bike: def __init__(self, model, make, color, type): # attributes self.model = model self.make = make self.color = color self.type = type dhanno = Bike("Standard 500", "Royal Enfield", "black", "cruiser") sakharam = Bike("RX-100", "Yamaha", "blue", "cafe racer") print(dhanno.type) print(sakharam.color)
Scratchpad #20
# class Book: # def __init__(self, name, no_of_pages, cover, category, author, price): # self.name = name # self.no_of_pages = no_of_pages # self.cover = cover # self.category = category # self.author = author # self.price = price # book1 = Book("Rich dad poor dad", 300, "softcover", "self-help", # "Robert Kiyosaki", 100) # print(book1) class User: total_users = 0 active_users = 0 def __init__(self, name, age, profession, country): self.name = name self._age = age # private attribute self.profession = profession self.country = country self.email = None User.total_users += 1 def greet(self): return f"Hello, my name is {self.name} and I am {self._age} years old" def set_email(self, new_email): self.email = new_email print("You email address was updated") def login(self): User.active_users += 1 print(f"{self.name} has now logged in") def logout(self): User.active_users -= 1 print(f"{self.name} has now logged out") user1 = User("Jack Smith", 20, "Programmer", "India") user2 = User("Jane Smith", 22, "Programmer", "UK") user1.login() user2.login() user1.logout() user2.login() user2.login() print(User.active_users) # -------------------------- # john = User("John Doe", 20, "Python Developer", "India") # jane = User("Jane Smith", 26, "Developer", "Bangladesh") # print(john.total_users) # print(jane.total_users) # print(User.total_users) # john.set_email("john@yahoo.co.in") # print(john.email) # john._age = 129 # print(john._age) # john.email = "john@gmail.com" # jane.profession = "System Administrator" # print(jane.profession) # print(john.email)
Scratchpad 21
from random import choice # class User: # total_users = 0 # def __init__(self, fn, ln, age): # self.first_name = fn # self.last_name = ln # self.age = age # User.total_users += 1 # def __repr__(self): # return f"**********\n{self.first_name} {self.last_name}\n***********" # def greet(self): # return f"Hello my name is {self.first_name} {self.last_name}" # def hello(self): # return "Hello World" # @classmethod # def get_total_users(cls): # return User.total_users # @classmethod # def generate_password(cls, length=12): # chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()" # password = '' # for _ in range(length): # password += choice(chars) # return password # user1 = User("john", "doe", 20) # user2 = User("jane", "smith", 26) # print(user1) # print(user2) # # print(user1.generate_password()) # # print(user1.first_name) # # print(user1.greet()) # # print(User.generate_password(10)) # # user1 = User("john", "doe", 20) # # print(user1.hello()) # # print(User.get_total_users()) # # user1 = User("john", "doe", 20) # # user2 = User("jane", "doe", 20) # # # print(user1.greet()) # # print(user2.greet()) # # # print(user1.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 # # @classmethod # # def div(cls, a, b): # # return a / b # # Math.add(10,2) # # Math.sub() # class User: # def __init__(self, fullname, age): # self.fullname = fullname # self.age = age # def login(self): # return 'You have now logged in' # def logout(self): # return 'You have now logged out' # def get_profile(self): # return "Your profile details: ...." # class Admin(User): # def create_group(self, name): # return f"{name} was successfully created" # def status(self): # return f"My name is {self.first_name} {self.last_name}" # # john = User("John", "Doe", 20) # jane = Admin("Jane Doe", 23) # print(jane.status()) # # # john.login() # # print(jane.create_group("python")) # # print(jane.login()) # # print(jane.get_profile()) # # name = "john" class User1: 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 f"My name is {self.first_name} {self.last_name}" jack = User1("jack", "smith", 20) jack.greet() def User2(first_name, last_name, age): def greet(): return f"My name is {first_name} {last_name}" return { "first_name": first_name, "last_name": last_name, "age": age, "greet": greet } def user(first_name, last_name, age): return { "first_name": first_name, "last_name": last_name, "age": age, } def greet(first_name, last_name): return f"My name is {first_name} {last_name}" jack = user("Jack", "Smith", 30) greet(jack["first_name"], jack["last_name"]) john = User1("John", "Doe", 20) jane = User2("Jane", "Doe", 25) print(john.first_name) print(john.greet()) print(jane["first_name"]) print(jane["greet"]())
Scratchpad #22
# 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 f"My name is {self.first_name} {self.last_name}" # @property # def age(self): # print("The age of the user was being accessed") # return self._age # @age.setter # def age(self, new_age): # if type(new_age) != int: # raise TypeError("Age can only be a number") # self._age = new_age # return new_age # # # Getter # # def get_age(self): # # print("The age of the user was being accessed") # # return self._age # # # Setter # # def set_age(self, new_age): # # if type(new_age) != int: # # raise TypeError("Age can only be a number") # # self._age = new_age # # return new_age # user1 = User("John", "Doe", 20) # print(user1.age) # # user1.set_age(30) # user1.age = 30 # print(user1.age) # # user1.set_age(30) # # user1.age = 30 # # user1.set_age("hello") # # user1._age = "" # # print(user1.get_age()) # # print(user1.get_age()) # # user1.set_age(21) # # print(user1.get_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 greet(self): # return f"My name is {self.first_name} {self.last_name}" # class Moderator(User): # def __init__(self, first_name, last_name, age, phone): # super().__init__(first_name, last_name, age) # self.phone = phone # def delete_comment(self): # return "Deleted comment" # user1 = User("John", "Doe", 23) # mod1 = Moderator("Jane", "Doe", 25, 123456789) # print(mod1.greet()) # print(mod1.delete_comment()) class Dog: def __init__(self, name, age): self.name = name self.age = age def talk(self): return "Bow Bow Bow" class Human: def __init__(self, name, age): self.name = name self.age = age def talk(self): return "Hello, How are you?" class Mutant(Human, Dog): def __init__(self, name, age): self.name = name self.age = age # def talk(self): # return "Hello, Bow are you?" john = Human("John Doe", 20) tyson = Dog("Tyson", 5) johnson = Mutant("JohnSon", 25) # print(john.talk()) # print(tyson.talk()) print(johnson.talk())
Scratchpad #23
# # 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 self.first_name # # class Moderator(User): # # def greet(self): # # return self.last_name # # user1 = User("John", "doe", 20) # # mod1 = Moderator("Jane", "doe", 22) # # print(user1.greet()) # # print(mod1.greet()) # # class Animal: # # def speak(self): # # raise NotImplementedError("Subclass needs to implement this method") # # class Dog(Animal): # # def speak(self): # # return "Hello, I want bread" # # class Cat(Animal): # # def speak(self): # # return "Hello, I want fish" # # an1 = Dog() # # an2 = Cat() # # print(an2.speak()) # # print(len([1, 2, 3, 4])) # 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, user): # return User("new born", user.last_name, 0) # def __repr__(self): # return self.first_name # user1 = User("John", "doe", 20) # user2 = User("Jill", "doe", 24) # user3 = user1 + user2 # print(user3) # print(len(user1)) # for num in [1, 2, 3]: # print(num) def my_for(iterable): iterator = iter(iterable) while True: try: print(next(iterator)) except StopIteration: break # my_for([1, 2, 3, 4]) while True: print("hello")
Scratchpad #24
# 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})" # def __iter__(self): # return self # def __next__(self): # if self.start < self.end: # 0 - 1 # num = self.start # self.start += self.step # return num # else: # raise StopIteration # c = Counter(0, 11, 2) # print(c) # for num in c: # print(num) # def count(num): # current = 1 # while current <= num: # yield current # current += 1 # c = count(10) # print(list(c)) # for num in c: # print(c) # for num in c: # print(num) # my_list = list(range(10000)) # for num in my_list: # 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 b count += 1 # print(fib_list(50000)) for num in fib_gen(50000): print(num) # SPACE COMPLEXITY # TIME COMPLEXITY def test(): """_summary_ """
Scratchpad #25
# class User: # def __init__(self, name, age): # self.name = name # self.age = age # def greet(self): # return f"Hello my name is {self.name} and I am {self.age} years old" # john = User("John De", 20) # print(john.greet()) # def math(a, b, fn): # return fn(a, b) # def add(a, b): # return a + b # result = math(10, 4, add) # print(result) # def sum(n, func): # total = 0 # for num in range(1, n + 1): # total += func(num) # return total # # def square(x): # # return x * x # print(sum(2, lambda x: x * x)) # from random import choice # def greet(person): # def get_mood(): # mood = ["Hey", "What!", "What the hell do you want!", "Get lost!"] # msg = choice(mood) # return msg # return f"{get_mood()} {person}" # print(greet("John")) # from random import choice # def make_greet_func(person): # def make_message(): # msg = choice( # ["Hey", "What!", "What the hell do you want!", "Get lost!"]) # return f"{msg} {person}" # return make_message # result = make_greet_func("john") # print(result()) # def stars(fn): # def wrapper(): # print("*" * 10) # fn() # print("*" * 10) # return wrapper # @stars # say_hello = stars(say_hello) # def say_hello(): # print("Hello World") # # say_hello() # # say_hello = stars(say_hello) # say_hello() # def make_upper_case(fn): # def wrapper(*args, **kwargs): # return fn(*args, **kwargs).upper() # return wrapper # @make_upper_case # say_hello = make_upper_case(say_hello) -> wrapper # def say_hello(message): # return message # @make_upper_case # def greet(message, person): # return f"{message}, {person}" # print(say_hello("hello john")) # print(greet("hello", "john"))
Banking App Start
Scratchpad #26
# class User: # def __init__(self, name, age): # self.name = name # self.age = age # user1 = User("John Doe", 20) # def count(num): # current = 1 # while current <= num: # yield current # current += 1 # for num in count(10): # print(num) from functools import wraps def make_upper_case(fn): """Decorator that uppercases the return value""" @wraps(fn) def wrapper(*args, **kwargs): """Wrapper function""" return fn(*args, **kwargs).upper() return wrapper @make_upper_case # greet = make_upper_case(greet) def greet(name): """Accepts a name (string) and return a greeting""" return f"Hello, {name}" @make_upper_case # say_message = make_upper_case(say_message) def say_message(name, message): """Accepts a name and a message and return them""" return f"{message} {name}" print(say_message.__doc__) print(say_message.__name__) print(greet.__doc__) # print(greet("John")) # print(say_message("John Doe", "Hi there"))
Scratchpad #27
# from functools import wraps # def make_stars(fn): # @wraps(fn) # wrapper = wraps(wrapper) # def wrapper(*args, **kwargs): # print("*************") # fn() # print("*************") # return wrapper # @make_stars # say_hello = make_stars(say_hello) # def say_hello(): # print("Hello World") # def greet(): # print("My name is john") # greet() # Dynamic Decorator # def inner(fn): # def wrapper(*args, **kwargs): # pass # return wrapper # def ensure_first_arg(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("pizza") # def fav_foods(*args): # print(args) # # fav_foods = ensure_first_arg("pizza")(fav_foods) # fav_foods( # "pizza", # "burger", # "vada pav", # ) # def ensure(*types): # def inner(fn): # def wrapper(*args, **kwargs): # "10", "23" # new_args = [] # ["10", 23] # for a, t in zip(args, types): # (("10", str), ("23", int)) # try: # new_args.append(t(a)) # 10 # except (ValueError, TypeError): # raise Exception("Something went wrong") # return fn(*new_args) # announce("10", 23) # return wrapper # return inner # @ensure(str, int) # announce = ensure(str, int)(announce) # def announce(msg, times): # print(f"{msg}\n" * times) # # wrapper # announce("10", "23") # wrapper("10", "23") # # announce(10, "20") # wrapper(10, "10") # # announce("hello", 23.6) # wrapper("hello", 23) # ============================================================================== from random import random def generate_account_no(length=9): return "".join(str(random() + 1).split("."))[0:length] class Bank: def __init__(self, name, initials, address, email, phone, ifsc): self.name = name self.initials = initials self.address = address self.email = email self.phone = phone self.ifsc = ifsc self.customers = [] def create_customer(self, first_name, last_name, email, phone, address, aadhar_no, pan_no, dob): customer = Customer(first_name, last_name, email, phone, address, aadhar_no, pan_no, dob, self.name) self.customers.append(customer) return customer class Customer: def __init__(self, first_name, last_name, email, phone, address, aadhar_no, pan_no, dob, bank): self.first_name = first_name self.last_name = last_name self.email = email self.phone = phone self.address = address self.aadhar_no = aadhar_no self.pan_no = pan_no self.dob = dob self.bank = bank self.account_no = generate_account_no() self.balance = 0 def __repr__(self): return f"{self.first_name} {self.last_name}:{self.account_no}:{self.balance}" def deposit(self, amount): self.balance += amount print( f"Amount of Rs. {amount} was deposited in your account. Current balance: {self.balance}" ) return self.balance def withdraw(self, amount): if amount > self.balance: raise Exception("Insufficient Balance") else: prev_balance = self.balance self.balance -= amount print( f"Amount of Rs. {amount} was debited from your account. Old Balance: {prev_balance}, New Balance: {self.balance}" ) return self.balance # Create the bank sbi = Bank("State Bank of India", "sbi", "Government Colony, Bandra East, Mumbai 400051", "support@sbi.com", 123456789, "sbi123") customer1 = sbi.create_customer("John", "Doe", "john@gmail.com", 9809987654, "Dadar", "1234567890", "123456", "12/1/2000") customer2 = sbi.create_customer("Jane", "Doe", "jane@gmail.com", 9809987654, "Dadar", "1234567890", "123456", "12/1/2000") customer1.deposit(1000) customer1.deposit(543) customer1.withdraw(202) print(sbi.customers)
Scratchpad #28
# file = open("hello.txt") # # print(file) # print(file.read()) # file = open("hello.txt") # print(file.read()) # file.close() # with open("hello.txt", "r") as file: # print(file.read()) # print(file.closed) # print(file.closed) # with open("world.txt", "w") as file: # file.write("Hello World\n") # file.write("This is another line of text. ") # file.write("Another sentence. Some more words\n") # file.write("Completed") # with open("hello.txt", "w") as file: # file.write("Hello World " * 1000000) # with open("world.txt", "a") as file: # file.write("NEW TEXT\n") # with open("world.txt", "r+") as file: # file.write("Welcome to your life!") # file.seek(0) # file.write("Hello World " * 10) # from csv import reader, DictReader # with open("data.csv") as file: # csv_data = reader(file) # for row in csv_data: # print(row) # with open("data.csv") as file: # csv_data = DictReader(file) # for row in csv_data: # print(row) # from csv import reader # with open("data.csv") as file: # csv_data = reader(file) # print(list(csv_data)) # def custom_csv_reader(file_path): # with open(file_path) as file: # data = file.read() # print(data.split('\n')) # custom_csv_reader("data.csv")
Scratchpad#29
# from csv import writer # with open("pokemon.csv", "w", newline="") as file: # csv_writer = writer(file) # csv_writer.writerow(["Name", "Type"]) # csv_writer.writerow(["Pikachu", "Electric shock"]) # csv_writer.writerow(["Charmendar", "Flamethrower"]) # csv_writer.writerow(["Squirtle", "Water cannon"]) # from csv import DictWriter # with open("users.csv", "w", newline="") as file: # headers = ["first_name", "last_name", "age"] # csv_writer = DictWriter(file, fieldnames=headers) # csv_writer.writeheader() # csv_writer.writerow({"first_name": "john", "last_name": "doe", "age": 20}) # csv_writer.writerow({"first_name": "jane", "last_name": "doe", "age": 20}) # csv_writer.writerow({"first_name": "jack", "last_name": "doe", "age": 20}) # 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): # return f"My name is {self.first_name} {self.last_name}" # with open("users.pickle", "rb") as file: # restored_data = pickle.load(file) # print(restored_data[0].greet()) # print(user1.greet()) # user1 = User("John", "Doe", 20) # user2 = User("Jane", "Smith", 22) # with open("users.pickle", "wb") as file: # pickle.dump((user1, user2), file) # print(user1.greet()) # print(user2.greet()) 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): return f"My name is {self.first_name} {self.last_name}" # with open("users.json") as file: # contents = file.read() # restored_data = jsonpickle.decode(contents) # print(restored_data[1].greet()) user1 = User("John", "Doe", 20) print(json.dumps(user1.__dict__)) # user2 = User("Jane", "Smith", 22) # with open("users.json", "w") as file: # json_data = jsonpickle.encode((user1, user2)) # file.write(json_data) # data = json.dumps(user1.__dict__) # print(data)
Scratchpad #30
# import sqlite3 # data = ("john", "doe", 20) # data_collection = [("john", "doe", 20), ("jane", "smith", 25), # ("jack", "roe", 33), ("jill", "roe", 45)] # conn = sqlite3.connect("python-students.db") # c = conn.cursor() # query = """INSERT INTO students VALUES (?, ?, ?)""" # for item in data_collection: # print(f"Adding {item[0]} to database") # c.execute(query, item) # c.executemany(query, data_collection) # # c.execute( # # "CREATE TABLE students (first_name TEXT, last_name TEXT, age INTEGER);") # # c.execute( # # 'INSERT INTO students (first_name, last_name, age) VALUES ("Amit", "Pawar", 19);' # # ) # # c.execute( # # 'INSERT INTO students (first_name, last_name, age) VALUES ("Sahil", "Gupta", 19);' # # ) # # data = c.execute("SELECT * FROM students;") # # print(list(data)) # # for item in data: # # print(item) # conn.commit() # conn.close() from pymongo import MongoClient from pprint import pprint client = MongoClient("mongodb://127.0.0.1:27017") db = client.python_students coll = db["students"] single_data = {"first_name": "john", "last_name": "doe", "age": 20} multiple_data = [ { "first_name": "jane", "last_name": "smith", "age": 23 }, { "first_name": "jack", "last_name": "ma", "age": 27 }, { "first_name": "richard", "last_name": "roe", "age": 34 }, { "first_name": "jill", "last_name": "pawar", "age": 19 }, ] # coll.insert_one(single_data) # coll.insert_many(multiple_data) data = coll.find_one({"last_name": "pawar"}) pprint(data)
Scratchpad 31
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from time import sleep browser = webdriver.Chrome("chromedriver.exe") browser.maximize_window() browser.get('https://www.youtube.com/') sleep(5) search_box = browser.find_element( By.XPATH, "/html/body/ytd-app/div[1]/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div[1]/div[1]/input" ) sleep(1) search_box.click() search_box.send_keys("wakanda forever", Keys.ENTER) sleep(5) movie = 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(2) movie = browser.find_element(By.PARTIAL_LINK_TEXT, 'Official') sleep(2) movie.click() # browser.get('https://web.whatsapp.com/') # sleep(20) # search_box = browser.find_element( # By.XPATH, # "/html/body/div[1]/div/div/div[3]/div/div[1]/div/div/div[2]/div/div[2]") # sleep(1) # search_box.click() # sleep(1) # search_box.send_keys("Python Evening", Keys.ENTER) # sleep(2) # message_box = browser.find_element( # By.XPATH, # "/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p" # ) # sleep(1) # message_box.click() # for num in range(20): # message_box.send_keys("HELLO WORLD!!", Keys.ENTER) # message_box = browser.find_element( # By.XPATH, # "/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p" # ) # message_box.click() # sleep(1000) # browser.close() from turtle import distance import pyautogui from pywinauto.application import Application from time import sleep app = Application(backend="uia").start("mspaint.exe") # print(pyautogui.size()) # pyautogui.moveTo(250, 450) # sleep(2) # distance = 200 # while distance > 0: # pyautogui.dragRel(distance, 0, 0.2) # distance = distance - 5 # pyautogui.dragRel(0, distance, 0.2) # pyautogui.dragRel(-distance, 0, 0.2) # distance = distance - 5 # pyautogui.dragRel(0, -distance, 0.2) # sleep(5) # pyautogui.screenshot("screen.png")
Scratchpad #32
# data = """ # <html> # <head> # <title>Hello World</title> # </head> # <body> # <h1>My Application</h1> # <div> # <h2 id="important">Some subtitle</h2> # <a href="https://google.com">Google</a> # <a href="https://yahoo.com">Yahoo</a> # </div> # <h2>Hello World</h2> # <div> # <p id="impPara"> # Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium # explicabo nihil, <b>in unde debitis esse</b> sed, nobis suscipit # molestiae consequatur, <em>voluptatibus commodi aliquam</em> voluptates # dolor voluptate qui harum eos accusamus. # </p> # <p> # Lorem ipsum dolor sit, amet consectetur adipisicing elit. Mollitia # deserunt cum in delectus repudiandae, quis labore laboriosam! Nisi # debitis dolor suscipit doloremque modi officiis praesentium cum cumque # exercitationem. Sit, corporis! # </p> # </div> # <hr /> # <hr /> # <hr /> # <ol> # <li class="blue-text"> # Lorem ipsum dolor sit, amet consectetur adipisicing elit. Eaque, # placeat. # </li> # <li class="blue-text imp-text"> # Lorem ipsum dolor sit, amet consectetur adipisicing elit. Eaque, # placeat. # </li> # <li> # Lorem ipsum dolor sit, amet consectetur adipisicing elit. Eaque, # placeat. # </li> # </ol> # </body> # </html> # """ # from bs4 import BeautifulSoup # soup = BeautifulSoup(data, "html.parser") # # FINDING # print(soup.body.h1) # print(soup.body.ol) ## Find by element name # h2 = soup.find("h2") # h2s = soup.find_all("h2") # lis = soup.find_all("li") # print(lis) # Find by id and class # result = soup.find(id="impPara") # result = soup.find(id="impPara") # result = soup.find_all(class_="blue-text") # print(result) # # Find by Attributes # result = soup.find(attrs={"href": "https://google.com"}) # result = soup.find(attrs={"id": "impPara"}) # print(result) # Selecting using CSS selectors # result = soup.select("li") # by element name # result = soup.select("h2") # by element name # result = soup.select(".blue-text") # by class name # result = soup.select("#impPara") # by id name # result = soup.select("[href]") # by attribute name # print(result) # result = soup.find("h2") # print(result.next_sibling.next_sibling) # print(result.parent.parent) # print(result.find_next_sibling()) # print(result.find_previous_sibling()) # print(result.find_parent()) # result = soup.find("h2") # result = soup.find("li") # print(result.get_text()) # result = soup.find("h2") # result = soup.find("a") # print(result["href"]) # import requests # from bs4 import BeautifulSoup # from csv import DictWriter # response = requests.get('https://arstechnica.com/') # # print(response.text) # soup = BeautifulSoup(response.text, "html.parser") # articles = soup.find_all(class_="article") # data = [] # for article in articles: # title = article.find("h2").get_text() # description = article.find(class_="excerpt").get_text() # author = article.find("span").get_text() # time = article.find("time").get_text() # link = article.find("a")["href"] # data.append({ # "title": title, # "description": description, # "author": author, # "time": time, # "link": link # }) # with open("articles.csv", "w", newline="") as file: # csv_writer = DictWriter( # file, fieldnames=["title", "description", "author", "time", "link"]) # csv_writer.writerows(data) def hello(): print(__name__) if __name__ == "__main__": print("HELLO WORLD")
Scratchpad #33
# from datetime import datetime # import multiprocessing # import threading # def dummy_func(x): # print(f"Job-{x} start: {datetime.now()}") # a = [] # for i in range(10000): # for j in range(5000): # a.append([i, j]) # a.clear() # print(f"Job-{x} end: {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__": # # 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}") # 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}")
Scratchpad #34
import tkinter as tkt from tkinter import font window = tkt.Tk() app_name = tkt.Label(text="Kamat-Pawar IT Force", foreground="white", background="red", padx=100, pady=5, font=font.Font(family="Arial", size=25)) frame1 = tkt.Frame() first_name = tkt.Label(text="First Name", font=font.Font(family="Arial", size=16), master=frame1) first_name_entry = tkt.Entry(master=frame1) last_name = tkt.Label(text="Last Name", font=font.Font(family="Arial", size=16), master=frame1) last_name_entry = tkt.Entry(master=frame1) submit_btn = tkt.Button( text="Submit Data", foreground="yellow", background="blue", command=lambda: print(first_name_entry.get(), last_name_entry.get())) app_name.pack() first_name.pack() first_name_entry.pack() last_name.pack() last_name_entry.pack() frame1.pack() submit_btn.pack() window.mainloop()