Python evening scratchpad

Python evening scratchpad

Scratchpad #1

# # print("Please enter your name:")

# name = input("Please enter your name: ")

# print(f"Hello, {name}")


# # USD to INR conversion
# usd = input("Please enter the dollar amount: ")  # "20"
# # inr = float(usd) * 72.98
# # print(type(usd))
# float_usd = float(usd)
# # print(type(float_usd))

# # print(f"${usd} in INR is {inr}")
# # print(f"${usd} in INR is {float(usd) * 72.98}")

# print(f"${usd} in INR is {int(usd) * int(70.123213)}")


usd = input("Please enter the dollar amount: ")
rate = input("Please enter the exchange rate: ")
# accept another input,(conversion rate)
# float_usd = float(usd)
# print(f"${usd} in INR is {float(usd) * int(70.123213)}")
print(f"${usd} in INR is {float(usd) * float(rate)}")


# int(45.324)

Scratchpad #2

# name = input("Which city do you stay in? ")

# if name == "mumbai":
#     print("Hello Mumbai")

# if name == "mojoland":
#     print("It's not a good city")

# if name == "chennai":
#     print("It's a good city")


# if name == "mumbai":
#     print("Hello Mumbai")
# elif name == "mojoland":
#     print("It's not a good city")
# elif name == "chennai":
#     print("It's a good city")
# else:
#     print("I have no idea about that city!")


# if name == "mumbai":
#     print("Hello Mumbai")
# else:
#     print("Cool")
# if name == "mojoland":
#     print("It's not a good city")
# if name == "chennai":
#     print("It's a good city")


# if name == "mojoland":
#     print("It's not a good city")

# if name == "chennai":
#     print("It's a good city")

# if name == "chennai":
#     print("It's a good city")

# if name == "chennai":
#     print("It's a good city")


# name = input("Which city do you stay in? ")

# if name != "mojoland":
#     print("You are welcome")
# else:
#     print("You are not welcome")


# age = int(input("Please enter your age: "))
# city = input("Please enter your city: ")

# if (age >= 21) or (not city != "mojoland"):
#     print("You are allowed to enter and buy drinks in the the concert")
# elif age >= 18 and city == "mojoland":
#     print("You are allowed to enter but not drink and not talk to anyone")
# else:
#     print("Get out! You can't enter")


# password = input("Please enter your secret password: ")

# if not password:
#     print("Please enter something")
# else:
#     print(password)


# if password == "":
#     print("Please enter something")
# else:
#     print(password)


# age = int(input("Please enter your age: "))
# city = input("Please enter your city: ")

# if ((age >= 18 and age <= 21) or age == 16) and city == "karachi":
#     print("You can buy as many guns as your want.")
# else:
#     print("You have to follow the rules")


player1 = input("Please enter Player1's choice: ")
player2 = input("Please enter Player2's choice: ")

# if player1 == "rock" and player2 == "scissor":
#     print("Player 1 wins")
# elif player1 == "rock" and player2 == "paper":
#     print("Player 2 wins")
# elif player1 == "rock" and player2 == "rock":
#     print("It's a tie")
# elif player1 == "scissor" and player2 == "paper":
#     print("Player 1 wins")
# elif player1 == "paper" and player2 == "scissor":
#     print("Player 2 wins")
# elif player1 == "scissor" and player2 == "scissor":
#     print("It's a tie")
# elif player1 == "paper" and player2 == "paper":
#     print("It's a tie")
# elif player1 == "paper" and player2 == "rock":
#     print("Player 1 wins")
# elif player1 == "scissor" and player2 == "rock":
#     print("Player 2 wins")


if (player1 == 'rock' and player2 == 'scissor') or (player1 == 'scissor' and player2 == 'paper') or (player1 == 'paper' and player2 == 'rock'):
    print("Player 1 wins")
elif  (player2 == 'rock' and player1 == 'scissor') or (player2 == 'scissor' and player1 == 'paper') or (player2 == 'paper' and player1 == 'rock'):
    print("Player 2 wins")
else:
    print("It's a tie")


if player1 == player2:
    print("it's a tie")
elif player1 == 'rock':
    if player2 == 'scissor':
        print("Player 1 wins")
    elif player2 == 'paper':
        print("Player 2 wins")
elif player1 == 'paper':
    if player2 == 'rock':
        print("Player 1 wins")
    elif player2 == 'scissor':
        print("Player 2 wins")
elif player1 == 'scissor':
    if player2 == 'paper':
        print("Player 1 wins")
else:
    print("Please only enter either rock, paper or scissor.")

Scratchpad #3

# for char in "rstforum":
#     print(char)


# [1,2,3,4,5,6,7,8,9,10]

# collection = range(1, 11)
# collection = [1,2,324,4,454,6,7,234,9,10,11,12,13,14,15,16]
# text = "This is so cool"

# for someValue in collection:
#     print(someValue)
#     print("----")
#     print("SOMETHING")

# for someValue in text:
#     print(someValue)


# for num in range(10):
#     print(num)

# times_to_remind_user = range(0, 4)

# for num in range(50, 100):
#     print(num)

# for num in range(0, 100, 10):
#     print(num)

# for num in range(100, 0, -10):
#     print(num)


# for num in range(10):
#     print(f"{num * 1000 / 3} times: WAKE UP!")


# for num in range(1, 21):
#     if num % 2 == 0:
#         print(f"{num}: Fizz is even")
#     elif num % 2 == 1:
#         print(f"{num}: Fizz is odd")
#     elif num == 5 and num == 16:
#         print(f"{num}: FizzBuzz")


# for num in range(1, 21):
#     if num == 5 or num == 16:
#         print(f"{num}: FizzBuzz")
#     elif num % 2 == 0:
#         print(f"{num}: Fizz is even")
#     else:
#         print(f"{num}: Fizz is odd")


# While Loops

# secret_password = input("Please enter your password: ")

# while secret_password != "balony1":
#     secret_password = input("Incorrect! Enter password again: ")

# secret_password = None
# while secret_password != "balony1":
#     secret_password = input("Incorrect! Enter password again: ")


# for num in range(1, 20):
#     print(num)


# # Infinite loop
# num = 1
# while num < 21:
#     print(num)
#     num += 1
#     # num = num + 1


# for num in range(3):
#     for num2 in range(10):
#         print(f"{num} {num2}")


# while True:
#   command = input("Type 'exit' to exit: ")
#   if (command == "exit"):
#     break

# for num in range(1, 21):
#   print(num)
#   if num == 5:
#     break


# RPS game

from random import randint

player_wins = 0
computer_wins = 0

winning_score = 3

while player_wins < winning_score and computer_wins < winning_score:
    print(f"PLAYER SCORE {player_wins}")
    print(f"COMPUTER SCORE {computer_wins}")

    player = input("Please enter your choice: ")
    if player == "quit":
        break

    print("\nROCK...PAPER...SCISSOR\n")

    rand_num = randint(0, 2)
    if rand_num == 0:
        computer = "rock"
    elif rand_num == 1:
        computer = "paper"
    elif rand_num == 2:
        computer = "scissor"

    print(f"Computer played {computer}")

    if (
        (player == "rock" and computer == "scissor")
        or (player == "scissor" and computer == "paper")
        or (player == "paper" and computer == "rock")
    ):
        player_wins += 1
        print("Player wins")
    elif (
        (computer == "rock" and player == "scissor")
        or (computer == "scissor" and player == "paper")
        or (computer == "paper" and player == "rock")
    ):
        computer_wins += 1
        print("Computer wins")
    else:
        print("It's a tie")


if player_wins > computer_wins:
    print("You got a beer")
else:
    print("You should settle in Mojoland!")


# player1 = input("Please enter Player1's choice: ")
# player2 = input("Please enter Player2's choice: ")

# if player1 == player2:
#     print("it's a tie")
# elif player1 == 'rock':
#     if player2 == 'scissor':
#         print("Player 1 wins")
#     elif player2 == 'paper':
#         print("Player 2 wins")
# elif player1 == 'paper':
#     if player2 == 'rock':
#         print("Player 1 wins")
#     elif player2 == 'scissor':
#         print("Player 2 wins")
# elif player1 == 'scissor':
#     if player2 == 'paper':
#         print("Player 1 wins")
# else:
#     print("Please only enter either rock, paper or scissor.")


# Exercise:
# Make a guessing game.
# random value = generate a random number between 0 and 10
# Keep asking the user to input his guess
# if guess is less than the random value, your tell the user, that his guess is too low
# if guess is greater than the random value, tell the user, that his guess is too high
# if guess == random value. Break out
# (optional) -> implement a "Do you want to play again?"

Scratchpad #4 and #5

# item1 = "iphone"
# item2 = "oneplus"
# item3 = "fridge"

# sourabh_cart = "iphone//oneplus//fridge"

# # using lists
# sourabh_cart = ["iphone", "oneplus", "fridge"]

# Shortcut for block commenting in VSCODE - Ctrl /

p_gmail = [
    "Your subscription to ****hub has expired",
    "Some other email",
    "Join us today! Let's do it!",
    "Naukri.com - you job application has been accepted"
]


# for email in p_gmail:
#     print(email)

# i = 0
# while i < len(p_gmail):
#     print(f"Value at {i} = {p_gmail[i]}")
#     i += 1

# my_fav_nums = [123,43,5,6,43,567]

# for num in my_fav_nums:
#     print(num * 2)


todo = []

while True:
    task = input("Please add a task: ")

    if task == "":
        print("Please add a valid task")
    elif task == 'q':
        break
    elif task == 'print':
        print(todo)
        print("--------------")
        for item in todo:
            print(f"* {item}")
        print("--------------")
    else:
        todo.append(task)

print("These are all your tasks")

for item in todo:
    print(item)

Scratchpad #6

# >>> profile = {"name": "Sonny", "profession": "actor", "age": 35, "gender": "female", "dob": "1/1/85"}
# >>>
# >>>
# >>> profile
# {'name': 'Sonny', 'profession': 'actor', 'age': 35, 'gender': 'female', 'dob': '1/1/85'}
# >>>
# >>> type(profile)
# <class 'dict'>
# >>>
# >>>
# >>> profile2 = dict(name="Patrick", profession="student", age=31, gender="male", dob="28/8/89")
# >>>
# >>> profile2
# {'name': 'Patrick', 'profession': 'student', 'age': 31, 'gender': 'male', 'dob': '28/8/89'}
# >>>
# >>>
# >>> type(profile2)
# <class 'dict'>
# >>>
# >>>
# >>> profile[0]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# KeyError: 0
# >>> profile["name"]
# 'Sonny'
# >>>
# >>>
# >>> dict(89="hello")
#   File "<stdin>", line 1
# SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
# >>> dict(name="hello")
# {'name': 'hello'}
# >>>
# >>>
# >>> {89:"hello"}
# {89: 'hello'}
# >>>
# >>>
# >>>
# >>> product = {"name": "AMD Ryzen Threadripper 3990X", "cores": 64, "SKU": "asdsad87632"}
# >>>
# >>>
# >>> product
# {'name': 'AMD Ryzen Threadripper 3990X', 'cores': 64, 'SKU': 'asdsad87632'}
# >>>
# >>> product["name"]
# 'AMD Ryzen Threadripper 3990X'
# >>>
# >>>
# >>> nums = [1,2,3,4,5]
# >>>
# >>> for num in nums:
# ...     print(num)
# ...
# 1
# 2
# 3
# 4
# 5
# >>> for detail in product:
# ...     print(detail)
# ...
# name
# cores
# SKU
# >>>
# >>> for detail in product.values():
# ...     print(detail)
# ...
# AMD Ryzen Threadripper 3990X
# 64
# asdsad87632
# >>>
# >>>
# >>> for detail in profile2.keys():
# ...     print(detail)
# ...
# name
# profession
# age
# gender
# dob
# >>>

# >>> for key,value in profile.items():
# ...     print(f"{key} - {value}")
# ...
# name - Sonny
# profession - actor
# age - 35
# gender - female
# dob - 1/1/85
# >>>
# >>> for key,value in profile2.items():
# ...     print(key)
# ...
# name
# profession
# age
# gender
# dob
# >>> for key,value in profile2.items():
# ...     print(f"The value of {key} is {value}")
# ...
# The value of name is Patrick
# The value of profession is student
# The value of age is 31
# The value of gender is male
# The value of dob is 28/8/89
# >>>
# >>> for item in profile2.items():
# ...     print(item)
# ...
# ('name', 'Patrick')
# ('profession', 'student')
# ('age', 31)
# ('gender', 'male')
# ('dob', '28/8/89')
# >>>

# >>> "name" in profile2
# True
# >>> "job" in profile2
# False
# >>>
# >>> "Patrick" in profile2
# False
# >>> "Patrick" in profile2.values()
# True
# >>>


# >>> profile2
# {'name': 'Patrick', 'profession': 'student', 'age': 31, 'gender': 'male', 'dob': '28/8/89'}
# >>>
# >>> profile
# {}
# >>> profile = profile2.copy()
# >>>
# >>> profile
# {'name': 'Patrick', 'profession': 'student', 'age': 31, 'gender': 'male', 'dob': '28/8/89'}
# >>>
# >>>
# >>> {}.fromkeys("a", "b", "c")
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: fromkeys expected at most 2 arguments, got 3
# >>> {}.fromkeys("name", "john")
# {'n': 'john', 'a': 'john', 'm': 'john', 'e': 'john'}
# >>>
# >>>
# >>> {}.fromkeys(["name", "age"], 23)
# {'name': 23, 'age': 23}
# >>> {}.fromkeys(["name", "age"], [1,2,3,4])
# {'name': [1, 2, 3, 4], 'age': [1, 2, 3, 4]}
# >>>
# >>>
# >>>
# >>>
# >>> {}.fromkeys(["name", "age", "dob"], None)
# {'name': None, 'age': None, 'dob': None}
# >>> {}.fromkeys(["name", "age", "dob"], 0)
# {'name': 0, 'age': 0, 'dob': 0}
# >>>
# >>>
# >>> score = {}.fromkeys(["tim", "john", "ram"], 0)
# >>> score
# {'tim': 0, 'john': 0, 'ram': 0}
# >>>
# >>>
# >>> score = {}.fromkeys([num for num in range(1,11)], None)
# >>>
# >>> score
# {1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None, 10: None}
# >>>
# >>>
# >>> myDict = {}.fromkeys("hello", "world")
# >>>
# >>> myDict
# {'h': 'world', 'e': 'world', 'l': 'world', 'o': 'world'}
# >>>
# >>> type(myDict)
# <class 'dict'>
# >>> myDict = {}.fromkeys(1, "world")
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: 'int' object is not iterable
# >>> myDict = {}.fromkeys(123, "world")
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: 'int' object is not iterable
# >>>
# >>>
# >>>


user1 = {
    "first_name": "John",
    "last_name": "Sinha",
    "email": "youcanseeme@gmx.com",
    "twitter": "@johnsha",
    "phone": 100,
}

# if user1.get("twitter") != None:
#     print(user1.get("twitter"))
# else:
#     print("This user doesn't not have a twitter account")


# print(user1.pop("phone"))
# print(user1)

# print(user1.popitem())
# print(user1.popitem())
# print(user1.popitem())
# print(user1)

# # Prints only the keys
# for item in user1:
#     print(item)

# # Prints the values
# for item in user1.values():
#     print(item)

# # Prints both the key and the value together
# for key, value in user1.items():
#     print(f"The value of {key} is {value}")


# # Dict Comprehension
# {print(f"The value of {key} is {value}") for key, value in user1.items()}


# my_dict = {"India": "New Delhi", "China": "Bejing", "Nepal": "Katmandu", "Bangaladesh": "Dhaka"}

# places = {country:f"{city} is the capital" for country,city in my_dict.items()}
# print(places)


# print({num: num**5 for num in [2,3,4]})
# print({num: str(num) + "HELLO" for num in [2,3,4]})


# string = "ABCDEFG"

# new_value = {string[i - 1]:i for i in range(1, len(string) + 1)}

# print(new_value)


numbers = [123,213,532,436,4576,322,332,435]
new_dict = {num ** 2: ("even" if (num ** 2) % 2 == 0 else "odd") for num in numbers}
print(new_dict)

dict_numbers = {"num1": 123, "num2": 214, "num3": 325}
dict_nums_new = {k:(f"{v} is even" if v % 2 == 0 else f"{v} is odd") for k,v in dict_numbers.items()}
print(dict_nums_new)

Scratchpad #7

# Tuple


# in_scams = {1992: "Harshad Mehta", "2G": "A Raja", "Kingfisher": "Mallaya"}

# in_scams2 = {(1992, 2000): "Harshad Mehta", (2020, "Corona"): "Pravin"}

# print(in_scams)
# print(in_scams2)


# offices = {(1.213132, 1.22313): "Mumbai Office", (0.1231243, 2.123214): "Pune Office"}

# print(offices[(1.213132, 1.22313)])


# # Sets

# my_set = {12,3,4,5,5,5,5,5,5,6,6,7,8,9,34}
# #{34, 3, 4, 5, 6, 7, 8, 9, 12}

# # for num in my_set:
# #     print(num)


# my_set.add(35)
# my_set.add(5)

# my_set.remove(5)
# # my_set.remove(102)
# my_set.discard(102)

# print(my_set)


# # Common SET Math Methods

# # Union

# good_cities.union(bad_cities)
# good_cities | bad_cities

# # Intersection
# good_cities.intersection(bad_cities)
# good_cities & bad_cities


# # Set Comprehensions

# {num // 2 for num in range(10)}



# >>> "hello".upper()
# 'HELLO'
# >>>
# >>>
# >>> HELLO.lower()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# NameError: name 'HELLO' is not defined
# >>> "HELLO".lower()
# 'hello'
# >>>
# >>>
# >>> "hello".upper().lower()
# 'hello'
# >>>
# >>> "hello".capitalize()
# 'Hello'
# >>> "hello world".capitalize()
# 'Hello world'
# >>>
# >>>
# >>> "If you are good at something never do it for money".find("at")
# 16
# >>> "If you are good at something never do it for money".find("you")
# 3
# >>> "If you are good at something never do it for money".find("you2")
# -1
# >>> "If you are good at something never do it for money".find("you ")
# 3
# >>> "If you are good at something never do it for money".find("money")
# 45
# >>>
# >>>
# >>>
# >>> "sonny".center(25)
# '         sonny         '
# >>>
# >>> "sonny".center(0)
# 'sonny'
# >>> "sonny".center(10)
# ' sonny  '
# >>>



def horn():
    print("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHH")
    print("OOOOOOOOOOOOOOOOOOOOOOOOOOOOOO")
    print("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNN")
    print("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKK")

horn

Scratchpad #8

# def say_hello():
#   print("Hello!")
#   print("Hello!")
#   print("Hello!")
#   print("Hello!")
#   print("Hello!")
#   print("Hello!")


# def say_hello():
#   print("Hey there!")
#   return ("Hello")
# #   print("Whats up!")

# # result = say_hello()

# # print(result)


# def say_goodbye():
#     print("good bye")

# say_goodbye()


# def square_of_10():
#     return 10 ** 2


# # say_hello()

# # say_goodbye()

# square_of_10()

# say_hello()


# from random import random

# # print(int(random() * 1000000))

# def flip_coin():
#     if random() > 0.5:
#         return "Heads"
#     else:
#         return "Tails"


# print(flip_coin())


# def add(first, second):
#     if type(first) == int and type(second) == int:
#         return first + second
#     else:
#         return "Please enter only integers"


# print(add(20, 5))


# def power_to(number, power):
#     return number ** power

# print(power_to(50, 3))



# def power_to(number, power, message):
#     return f"{message} - {number ** power}"

# # # print(power_to(50, 3))
# # print(power_to(50, 3, "Hello World"))
# print(power_to("Hello World", 50, 3))


# def filter_out(info):
#     if (info.lower().find("delhi") == -1):
#         return "Your job request has been accepted"
#     else:
#         return "Sorry there was no job, it was a mistake"


# user_input = input("What is your name and where are you from? ")

# print(filter_out(user_input))





# def sum_odd_numbers(numbers):
#     total = 0

#     for num in numbers:
#         if num % 2 != 0:
#             total += num

#     return total


# print(sum_odd_numbers([1,2,3,4,5]))




# def power_to(number=5, power=2, message="The answer is"):
#     return f"{message} - {number ** power}"


# # print(power_to(10, 4, "Hello"))
# # print(power_to(10))
# print(power_to())


# def add(a, b):
#     return a + b

# def subtract(a, b):
#     return a - b

# def divide(a, b):
#     return a / b


# def math(a,b,fn=add):
#     return fn(a,b)


# print(math(10,120,subtract))
# print(math(10,120))


# def full_name(first, last):
#     return "Your name is " + first + " " + last + "."


# def div(dividend, divisor):
#     return dividend / divisor



# # print(full_name("Kute", "Pravin"))
# print(div(2, 10))

# print(div(divisor=2, dividend=10))


# Scope

# result = "Hello World"

# def power_to(number=5, power=2, message="The answer is"):
#     dog = "Beagle"
#     if number == 10:
#         print(dog)
#         name = "Arnold"
#     print(name)
#     result = f"{message} - {number ** power}"
#     # print(result)
#     return result

# print(dog)

# # print(power_to())
# print(power_to(10))


# num = 100

# def power_to(number=5, power=2, message="The answer is"):
#     global num
#     num += 200
#     return f"{message} - {number ** power}"


# print(power_to(10))

# print(num)



# def outer():
#     count = 0
#     def inner():
#         nonlocal count
#         count += 1
#         return count
#     return inner()

# outer()

# nonlocal count
# count += 10
# print(count) # ERROR


def power_to(number=5, power=2, message="The answer is"):
    """This is a little information about this function. It will do some exponent math."""
    return f"{message} - {number ** power}"


print(power_to(10))

print(power_to.__doc__)

Scratchpad #9

# def add(*nums):
#     print(nums)
#     total = 0
#     for num in nums:
#         total += num
#     return total

# print(add(1,2,34,4,34,-1000,6,743,3,))


# def printme(message, *names):
#     for name in names:
#         print(f"{message} {name}")


# printme("Praveen", 100, "Ronak", True, "Ninad", "Ankit")


# def entry(*names):
#     if 'delhi' in names:
#         print("You are not allowed in here")
#     else:
#         print("Please come in")


# entry('Definite', True)



# def profile(**details):
#     # print(details)

#     for k,v in details.items():
#         print(f"{k} - {str(v).upper()}")
#     # print(f"{first_name} {last_name}")


# profile(last_name="Mukherjee", first_name="Sourabh", age=33, job="Software Developer")


# def show_info(a, b, *args, role="moderator", **kwargs):
#     return [a, b, args, role, kwargs]

# print(show_info(1, 2, 3, first_name="John", last_name="Wick"))

# # unpacking
# def add(*nums):
#     total = 0
#     for num in nums:
#         total += num
#     return total

# nums = [1,2,3,4]

# print(add(*nums))


# def say_name(first, last):
#     print(f"My name is {first} {last}.")

# name = {"first": "Don", "last_name": "Corleone"}

# # say_name("Lucifer", "Morningstar")
# say_name(**name)
# say_name(first="Don", last_name="Corleone")


# def say_name2(**names):
#     for k,v in names.items():
#         print(f"My {k} is {v}")


# say_name2(first="Don", last_name="Corleone", profession="Mafia")


# def square(a):
#     return a * a


# print(square(10))

squared = lambda a,b: a * a * b
# print(squared(20,10))
# print(type(squared))

# squared = 10
# print(squared)
# print(type(squared))


# def math(a,b,fn):
#     return fn(a,b)


# def add(a,b):
#     return a + b

# print(math(10,20,add))

# print(math(200,12,lambda a,b: a * b))
# print(math(200,12,lambda a,b: a * b + (a ** 2)))


# nums = [1,2,3,4,5,6,7,8]

# triples = map(lambda num: num ** 3, nums) # map object
# # quads = [num**4 for num in nums]
# print(triples)

# mul5 = [num * 5 for num in triples]
# print(mul5)

# print(dict(triples))
# print(list(triples))

# print(list(triples))
# print(quads)


names = ["Gordon Gecko", "Definite", "Will Smith", "Willis", "SSR", "Harvey Spectre", "Amir Khan", "Vijay Chauhan", "Bruce Wayne"]

filtered_list = list(filter(lambda name: name[0].lower() == 'w', names))

print(filtered_list)

Scratchpad #10

# Exercise 8


# def manipulate_list(list, command, location, value=None):
#     if command == "add" and location == "end":
#         if value:
#             list.append(value)
#             print(list)
#         else:
#             print("Please provide a value")
#     elif command == "add" and location == "front":
#         if value:
#             list.insert(0, value)
#             print(list)
#         else:
#             print("Please provide a value")
#     elif command == "remove" and location == "end":
#         if not value:
#             list.pop()
#             print(list)
#         elif value != list[-1]:
#             print(f"{value} is not the last value in the list")
#             print(list)
#         else:
#             list.pop()
#             print(list)
#     elif command == "remove" and location == "front":
#         if not value:
#             list.pop(0)
#             print(list)
#         elif value != list[0]:
#             print(f"{value} is not the first value in the list")
#             print(list)
#         else:
#             list.pop(0)
#             print(list)


# my_list = [1, 2, 3, 4, 5]
# manipulate_list(my_list, "add", "end", 100)
# manipulate_list(my_list, "add", "front", 50)
# manipulate_list(my_list, "remove", "end", 50)
# manipulate_list(my_list, "remove", "front", 50)

# manipulate_list(my_list, "remove", "end")
# manipulate_list(my_list, "add", "end")

# Ex. 9


# def is_palindrome(str):
#     return str.lower() == str.lower()[::-1]


# print(is_palindrome("anna"))


# Filter and map -> console output
# >>> nums = [1,2,3,4,5]
# >>>
# >>> mapped = map(lambda num: num + (num * 2), nums)
# >>>
# >>> mapped
# <map object at 0x00000154D7637FA0>
# >>> list(10)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: 'int' object is not iterable
# >>> list("hello")
# ['h', 'e', 'l', 'l', 'o']
# >>> list(mapped)
# [3, 6, 9, 12, 15]
# >>> mapped = list(map(lambda num: num + (num * 2), nums))
# >>> mapped
# [3, 6, 9, 12, 15]
# >>>
# >>>
# >>> nums
# [1, 2, 3, 4, 5]
# >>>
# >>>
# >>> filtered = list(filter(lambda num: num % 2 != 0, nums))
# >>> filtered
# [1, 3, 5]
# >>>
# >>> category = ["apple", "samsung", "lenovo", "hp", "dell", "asus"]
# >>>
# >>> filtered = filter(lambda cat: cat == "apple", category)
# >>>
# >>> list(filtered)
# ['apple']
# >>>
# >>> user = ["apple", "Karbonn"]
# >>>
# >>> filtered = filter(lambda cat: cat in user, category)
# >>>
# >>> list(filtered)
# ['apple']
# >>>


# names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"]

# survived = list(
#     map(lambda name: f"Winner: {name}", list(filter(lambda name: len(name) < 5, names)))
# )

# print(survived)

# names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"]
# # print(all(names))

# # print(all([name[0] == "J" for name in names]))
# # print([name[0] == "J" for name in names])


# print(any(name for name in names if len(name) > 3))


# nums = (123, 123, 21314, 5, 643, 2, 23321, 1)

# print(sorted(nums, reverse=True))


# >>> sorted("Hello")
# ['H', 'e', 'l', 'l', 'o']
# >>> sorted("Hello2324")
# ['2', '2', '3', '4', 'H', 'e', 'l', 'l', 'o']
# >>> sorted("Hello2324JAS")
# ['2', '2', '3', '4', 'A', 'H', 'J', 'S', 'e', 'l', 'l', 'o']
# >>> sorted([12,234,4,5,6])
# [4, 5, 6, 12, 234]
# >>> tuple(sorted([12,234,4,5,6]))
# (4, 5, 6, 12, 234)
# >>> tuple(sorted([12,234,4,5,6,6,6]))
# (4, 5, 6, 6, 6, 12, 234)
# >>> set(sorted([12,234,4,5,6,6,6]))
# {4, 5, 6, 234, 12}
# >>> sorted(set(sorted([12,234,4,5,6,6,6])))
# [4, 5, 6, 12, 234]
# >>>

# # Sidenote - generators
# import sys

# # print(sys.getsizeof([1123213, 213, 213, 213, 21, 321, 3, 213, 213, 21, 3]))

# lst = [num * 10000 for num in range(0, 1000)]
# gen = (num * 10000 for num in range(0, 1000))

# print(sys.getsizeof(lst))
# print(sys.getsizeof(gen))


# >>> reversed("hello")
# <reversed object at 0x000002304493A550>
# >>>
# >>> list(reversed("hello"))
# ['o', 'l', 'l', 'e', 'h']
# >>>
# >>>
# >>> "".join(reversed("hello"))
# 'olleh'
# >>>
# >>>
# >>> abs(-33.3333)
# 33.3333
# >>> abs(-33.3)
# 33.3
# >>> abs(0)
# 0
# >>> abs(-0)
# 0
# >>>
# >>>
# >>>
# >>> sum([1,2,3])
# 6
# >>> sum([1,2,3,-4])
# 2
# >>> sum([1,2,3])
# 6
# >>> sum([1,2,3], 100)
# 106
# >>> sum([1,2,3], 5)
# 11
# >>> sum(range(1, 21), 5)
# 215
# >>> sum(range(1, 21), 1000)
# 1210
# >>>
# >>>
# >>>
# >>> round(99.99)
# 100
# >>> round(99.94)
# 100
# >>> round(99.49)

ages = [23, 4, 532, 23, 45, 21, 98]
names = [
    "Hitler",
    "Elon Musk",
    "Warren Buffet",
    "Kim Jon Un",
    "Nikola Tesla",
]
birth_place = ["Austria", "South Africa", "New York", "North Korea", "USA"]

print(list(zip(names, ages, birth_place)))

Scratchpad #11

# import pdb

# # Raise error


# def color_text(text, color):
#     colors = ("red", "green", "yellow", "white", "blue")
#     pdb.set_trace()
#     # print(type(color))

#     if color not in colors:
#         raise ValueError("Please enter a supported color")

#     if type(color) is not str:
#         raise TypeError("Please enter a supported color string")

#     return f"{text} IN {color.upper()}"


# print(color_text("The apple doesn't fall too far from the tree.", 10))


# try:
#     print(color_text("The apple doesn't fall too far from the tree.", 10))
# except (TypeError, ValueError) as err:
#     print("Some error")
#     print(err)


# try:
#     # attempt
#     num = int(input("Please enter a number: "))
# except TypeError:
#     # if unsuccessful
#     print("That's not a number!")
# else:
#     # if successful
#     print(num * 100)
# finally:
#     # runs either way (in the end). Whether success or error
#     print("Runs no matter what!")


# Write a function called inc_dec_list which accepts a list of numbers
# and a command. If the command is "increase" then then add 1 to all
# the numbers in the list and return that list. If the command is
# "decrease" then subtract 1 instead. Use the map function to achieve this.


# def inc_dec_list(num_list, command):
#     if command == "increase":
#         return list(map(lambda n: n + 1, num_list))
#     elif command == "decrease":
#         return list(map(lambda n: n - 1, num_list))
#     else:
#         return "Unknown Command"


# print(inc_dec_list([10, 20, 30, 40, 50], "increment"))


# num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# result = list(filter(lambda n: n < 7, num_list))

# print(num_list)
# print(result)


names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"]
survived = list(
    map(lambda name: f"Winner: {name}", list(filter(lambda name: len(name) < 5, names)))
)
print(survived)

Scratchpad #14

# Module

# import random

# # print(random.random() * 100)
# # print(random.randint(10, 100))

# # def random():
# #     # code


# # import random
# import random as cool


# names = ["Donald Trump", "Kanye West", "Amir Khan", "Ninad Dubai", "Prathamesh Kurla"]

# # value = random.choice(["Donald Trump", "Kanye West", "Amir Khan"])
# value = cool.choice(["Donald Trump", "Kanye West", "Amir Khan"])

# print(names)
# # random.shuffle(names)
# cool.shuffle(names)
# print(names)

# # print(value)


# from random import randint as koi_number, choice as pasand, shuffle
from random import *

# print(randint(0, 10))
# print(koi_number(0, 50))
# print(pasand([1, 2, 3, 4, 5]))


print(randint(10, 100))
print(random())
print(choice(["first", "second"]))

Scratchpad #16

class Email:
    def __init__(self, to, cc, bcc, subject, message):
        self.to = to
        self.cc = cc
        self._bcc = bcc  # private attribute
        # self.__bcc = bcc  # Mangled attribute - _Email__bcc
        self.subject = subject
        self.message = message
        self.sender = "Gmail"

    def print_email(self):
        print(
            f"To: {self.to}\nCC: {self.cc}\nSubject: {self.subject}\nMessage: {self.message}"
        )

    # Getter method
    def get_bcc(self):
        return self._bcc

    # Setter method
    def set_bcc(self, email):
        self._bcc = email


# class User:
#     def __init__(self, name, dob, aadhar_no):
#         self.name = name
#         self._dob = dob
#         self._addhar_no = aadhar_no


my_email = Email(
    "john@gmail.com",
    None,
    "jack@outlook.com",
    "I am trying to install Numpy!",
    "It isn't happening.",
)

my_email2 = Email(
    "john2@gmail.com",
    "jon_snow@got.com",
    "jack2@outlook.com",
    "You know nothing",
    "Jon Snow. - Igrite",
)

print(my_email.to)
print(my_email.cc)
print(my_email.subject)
print(my_email.message)
print(my_email._Email__bcc)
print(my_email.sender)

my_email.to = "COOLMAN@COOLMAN.com"
my_email.sender = "Outlook.com"

print(my_email.to)
print(my_email.sender)

print(dir(my_email))


print(f"To: {my_email2.to}\nSubject: {my_email2.subject}")


my_email2.print_email()

print(my_email2.get_bcc())
my_email2.set_bcc("hound@lannister.com")
print(my_email2.get_bcc())


# Create a new class. Dog.
# Attributes: name, breed, age, _owner
# getter and setter method for getting and setting _owner attribute

Scratchpad 25-26 (Decorators)

# def add(a, b):
#     return a + b

# result = add(10,20)


# Make uppercase decorator
def make_upper_case(fn):
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs).upper()

    return wrapper


@make_upper_case
def say_hello(name):
    return f"Hello, {name}."


@make_upper_case
def custom_hello(msg, name):
    return f"{msg} {name}"


@make_upper_case
def add(a, b, c):
    result = a + b + c
    return f"The result of adding {a}, {b}, {c} is {result}"


print(add(c=50, a=10, b=1000))


# say_hello = make_upper_case(say_hello)

print(say_hello("hello world"))  # wrapper(arg) -> HELLO, HELLO WORLD!
print(say_hello(1000))  # wrapper(arg) -> HELLO, HELLO WORLD!


# message = custom_hello("Hey bruv", "John Doe")
# print(message)


# # def add(*args):
# #     print(args)
# #     return args[0] + args[1]
# # print(add(10))


# import time
from time import time


# def sum_gen(value):
#     print("Executing sum_gen")
#     start_time = time()
#     result = sum(num for num in range(value))
#     end_time = time()
#     print(f"Total time elapsed: {end_time - start_time}")
#     return result


# def sum_list(value):
#     print("Executing sum_list")
#     start_time = time()
#     result = sum([num for num in range(value)])
#     end_time = time()
#     print(f"Total time elapsed: {end_time - start_time}")
#     return result


# Speed test decorator
def speed_test(fn):
    def wrapper(*args, **kwargs):
        print(f"Executing {fn.__name__}")
        start_time = time()
        result = fn(*args, **kwargs)
        end_time = time()
        print(f"Total time elapsed: {end_time - start_time}")
        return result

    return wrapper


@speed_test
def sum_gen(value):
    return sum(num for num in range(value))


@speed_test
def sum_list(value):
    return sum([num for num in range(value)])


@speed_test
def greet(name):
    return f"Hello {name}"


print(sum_gen(1000))
print(sum_list(1000))
print(greet("John Doe"))


# Limit arguments decorator
def limit_args(fn):
    def wrapper(*args, **kwargs):
        if len(args) <= 2 or len(args) < 5:
            return fn(*args, **kwargs)
        else:
            return "Either too many or too less arguments"

    return wrapper


@limit_args
def add(*args):
    return sum(args)


print(add(1, 23, 432, 22, 1, 1, 1, 223))
print(add(1, 23, 432, 22))
print(add(1, 1))


# Authenticate/authorize decorator
def authenticate(fn):
    def wrapper(*args, **kwargs):
        if args[0]["role"] == "admin":
            return fn(*args, **kwargs)
        else:
            return "NOT AUTHORIZED"

    return wrapper


@authenticate
def access_page(user):
    return "SECRET CONTENT"


user1 = {"name": "John Doe", "username": "john123@gmail.com", "role": "admin"}
print(access_page(user1))


# def add(*args):
#     return sum(args)


# my_nums = [1, 2, 34, 5, 6, 7, 8]

# # print(add(121, 3223, 1, 1, 11, 2))
# print(add(*my_nums))

Scratchpad #27

# file = open("hello.txt")
# # print(file)

# print(file.read())


# hello_file = open("hello.txt")
# # print(hello_file)

# hello_file_contents = hello_file.read()

# print(hello_file_contents)


# file = open("hello.txt")
# print(file.readline())
# print(file.readline())
# print(file.readline())


# with open("hello.txt", "r") as hello_file:
#     print(hello_file.read())


# with open("hello.txt", "w") as file:
#     file.write("This is written programmatically.\n" * 10)
#     file.write("This is written programmatically.\n" * 10)

# with open("hello2.txt", "w") as file:
#     file.write("Hello World!\n")


# with open("hello2.txt", "a") as file:
#     file.seek(0)
#     file.write("Hello Universe\n")


# with open("hello3.txt", "r+") as file:
#     file.seek(25)
#     file.write("COOL" * 5)


def copy_file(filename, new_filename):
    with open(filename) as file:
        og = file.read()

    with open(new_filename, "w") as file:
        file.write(og)


copy_file("hello2.txt", "SOMETHING.txt")


def find_and_replace(filename, term, replacement):
    with open(filename, "r+") as file:
        text = file.read()
        new_text = text.replace(term, replacement)
        file.seek(0)
        file.write(new_text)


find_and_replace("hello2.txt", "Universe", "Multiverse")

Scratchpad 28

from csv import reader

with open("house_candidate.csv") as file:
    csv_reader = reader(file)  # iterator
    next(csv_reader)
    grand_total_votes = 0
    for row in csv_reader:
        # print(row[4])
        if row[4] == "True":
            grand_total_votes += int(row[3])
        # print(row[1])

print(grand_total_votes)

# --------

from csv import DictReader

with open("house_candidate.csv") as file:
    csv_reader = DictReader(file)
    for row in csv_reader:
        print(f"Party Name: {row['party']}")

# ----------------

from csv import writer, reader

with open("house_candidate.csv") as file:
    csv_reader = reader(file)

    with open("actors.csv", "w", newline="") as file:
        csv_writer = writer(file)
        for row in csv_reader:
            csv_writer.writerow(row)

# -----------------

from csv import DictWriter

with open("actors.csv", "w", newline="") as file:
    headers = ["Actor Name", "Gender", "Film"]
    csv_writer = DictWriter(file, fieldnames=headers)
    csv_writer.writeheader()
    csv_writer.writerow({"Actor Name": "Paul Walker", "Gender": "Male", "Film": "FNF"})
    csv_writer.writerow(
        {"Actor Name": "Gal Gadot", "Gender": "Female", "Film": "Wonder Woman"}
    )

# =------------

import pickle


class Human:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Name: {self.name}\nAge: {self.age}"


vishal = Human("Vishal", 28)
vaibhav = Human("Vaibhav", 22)
ankit = Human("Ankit", 21)

# print(vishal)
# print(vaibhav)
# print(ankit)

# with open("humans.pickle", "wb") as file:
#     pickle.dump((vishal, vaibhav, ankit), file)


with open("humans.pickle", "rb") as file:
    saved_humans = pickle.load(file)
    print(saved_humans[1])


# ----------------------------
# ----------- PROJECT
# ----------------------------

from random import choice


class Account:
    def __init__(
        self,
        first_name,
        last_name,
        address,
        phone,
        dob,
        email,
        pan_no,
        bank_name,
        bank_initial,
    ):
        # ...
        self.balance = 1000
        self.account_no = Account.gen_acc_no(bank_initial)
        self.username
        self.password

    @classmethod
    def gen_acc_no(cls, bank_initial):
        alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        nums = "0123456789"
        account_no = [bank_initial]
        i = 0
        while i < 8:
            account_no.append(choice([choice(alpha), choice(nums)]))
            i += 1
        return account_no

    # repr -> ac-no, customer, email

    # create a property and setter for `name`

    # functions:
    def deposit(self, amount):
        """Print a string. Also return the new balance"""
        prev_bal = self.balance
        self.balance += amount
        pass

    def withdraw(self, amount):
        pass


class Bank:
    def __init__(self, name, branch, address, ifsc):
        self.accounts = []
        # create a new csv -> write only the headers
        pass

    # create __repr__

    # add new account
    #

    # get all account


#####
sbi = Bank()

john_doe = Account()

sbi.add_new_account(john_doe)


sbi.get_all_accounts

Scratchpad 29 and 30

# import json
# import jsonpickle


# class User:
#     def __init__(self, first_name, last_name, age, verified):
#         self.first_name = first_name
#         self.last_name = last_name
#         self.age = age
#         self.verified = verified

#     def greet(self):
#         return "Hello World!"


# # john = User("John", "Doe", 25, True)

# # # print(john.__dict__)
# # # print(json.dumps(john.__dict__))


# # with open("users.json", "w") as file:
# #     # stored = jsonpickle.encode(john)
# #     file.write(jsonpickle.encode(john))

# with open("users.json") as file:
#     contents = file.read()
#     john = jsonpickle.decode(contents)
#     print(john)
#     print(john.greet())


# # print(john)

from bs4 import BeautifulSoup

data = """
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>My website</title>

        <style>
            .special {
                color: green;
                font-weight: bold;
            }
            #main {
                color: red;
            }
        </style>
    </head>
    <body>
        <h1 id="main">My website name</h1>
        <h2 class="special special2">This is my subtitle</h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed porta enim vel mauris
            dignissim, ac tempus justo rutrum. Nulla in vestibulum mi, vitae aliquam dui. Nunc orci
            metus, volutpat vel tortor ac, finibus iaculis nisi. Curabitur eleifend, orci at
            vehicula mattis, tellus metus fringilla nulla
        </p>
        <div>
            <h4 class="price product_label info">Product Price:</h4>
            <span class="price">$9.99</span>
            <a href="https://google.com">Google</a>
            <article class="first_para">
                Ut dictum urna diam, sit amet convallis nisi finibus eu. Maecenas dictum erat id
                porta ultrices. <strong>Nulla fringilla, sem ut accumsan interdum</strong>, purus
                purus mollis diam, sed pretium sapien lectus a libero. Phasellus rutrum vulputate
                eros eu imperdiet. Nam non malesuada purus.
            </article>
            <ul>
                <li class="special" id="sample">Nam quis risus eleifend, pretium quam eu, finibus massa.</li>
                <li class="special">
                    Donec vitae justo eu risus bibendum faucibus et vitae magna. Mauris congue diam
                    nec porttitor egestas.
                </li>
                <li>
                    Nam vel tincidunt lectus. Morbi molestie lacus id leo faucibus posuere. Sed eu
                    pretium justo. <em>Phasellus enim lectus</em>, rhoncus eu consequat ut,
                    facilisis eu velit.
                </li>
            </ul>
        </div>
        <div id="ending">
            <a href="https://yahoo.com" class="special">Yahoo</a>
            <img
                src="https://rukminim1.flixcart.com/flap/700/700/image/4224c093ab3f6206.jpg"
                alt="Image Description"
            />
            <p>This is some cool text.</p>
        </div>
    </body>
</html>
"""

soup = BeautifulSoup(data, "html.parser")

# print(type(soup))
# print(soup.body.div.ul)

# Finding
# h2 = soup.find("h2")
# print(type(h2))

# print(soup.find("div"))
# print(soup.find("ul"))
# print(soup.find("li"))

# all_lis = soup.find_all("li")
# print(type(list(all_lis)))

# print(soup.find(id="ending"))
# print(soup.find(class_="special"))
# print(soup.find_all(class_="special"))
# print(soup.find(href="https://google.com"))


# CSS Selectors

# print(soup.select(".special"))
# print(soup.select("h1"))
# print(soup.select("#ending"))


# print(soup.select(".special")[0])

# print(soup.select("[src]"))
# print(soup.select("[href]"))


# for element in soup.select(".special"):
#     print(element.get_text())
#     print(element.name)
#     print(element.attrs)
#     print(element.attrs['href'])


# spl_element = soup.find(class_="special")

# print(spl_element.get_text())


# for element in soup.select("a"):
#     print(element.attrs['href'])


# div_data = soup.find("div")

# print(div_data)
# print(div_data.get_text())


doc_body = soup.find("body")

# print(doc_body.contents)
# print(doc_body.contents[1])
# print(doc_body.contents[1].parent)
# print(doc_body.contents[1].parent.parent)
# print(doc_body.contents[1].next_sibling.next_sibling)

# print(doc_body.contents[1].find_next_sibling())
# print(doc_body.contents[1].find_previous_sibling())

print(doc_body.contents[1].find_next_sibling(class_="special"))


print(doc_body.contents[1].find_parent)

Scratchpad #33

import openpyxl

# # Create a new excel sheet

# wb = openpyxl.Workbook()
# sheet = wb.active

# sheet.title = "My Sheet"
# print(f"New Sheet title: {sheet.title}")

# c1 = sheet.cell(row=1, column=1)
# c1.value = "First Name"

# c2 = sheet.cell(row=1, column=2)
# c2.value = "Last Name"

# sheet["C1"].value = "Phone No."
# sheet["D1"].value = "Email"


# wb.save(
#     r"C:\Users\rahul.LAPTOP-IB8N85JR\Desktop\Training\Python\Python Evening 12\Scratchpads\Students.xlsx"
# )


# data = [
#     {
#         "first_name": "John",
#         "last_name": "Doe",
#         "phone": "887654332",
#         "email": "john@doh.com",
#     },
#     {
#         "first_name": "Jane",
#         "last_name": "Doe",
#         "phone": "887698076",
#         "email": "jane@doh.com",
#     },
#     {
#         "first_name": "Jack",
#         "last_name": "Doe",
#         "phone": "665789876",
#         "email": "jack@doe.com",
#     },
# ]


path = r"C:\Users\rahul.LAPTOP-IB8N85JR\Desktop\Training\Python\Python Evening 12\Scratchpads\Students.xlsx"
wb = openpyxl.load_workbook(path)
sheet = wb.active


data = [
    ["John", "Doe", "887654332", "john@doh.com"],
    ["Jane", "Doe", "887698076", "jane@doh.com"],
    ["Jack", "Doe", "665789876", "jack@doh.com"],
]

i = 2
while i < (len(data) + 2):
    j = 1
    # while j < (len(data) + 1):
    while j < 5:
        sheet.cell(row=i, column=j).value = data[i - 2][j - 1]
        j += 1
    i += 1

wb.save(path)
print("Task completed")

Scratchpad #34 #35

# import openpyxl
# from csv import reader

# # Reading CSV
# with open("house_candidate.csv") as file:
#     csv_reader = reader(file)
#     all_data = []
#     next(csv_reader)
#     for row in csv_reader:
#         all_data.append(row)

# # Create our excel workbook obj
# wb = openpyxl.Workbook()

# # Create a new sheet
# sheet = wb.active
# sheet.title = "House Candidates"

# sheet2 = wb.create_sheet("sheet2")

# # Write headers
# sheet["A1"] = "district"
# sheet["B1"] = "candidate"
# sheet["C1"] = "party"
# sheet["D1"] = "total_votes"
# sheet["E1"] = "won"

# # Write data to sheet
# i = 2
# while i < (len(all_data) + 2):
#     j = 1
#     while j < (len(all_data[0]) + 1):
#         sheet.cell(row=i, column=j).value = all_data[i - 2][j - 1]
#         j += 1
#     i += 1

# wb.save(
#     r"C:\Users\rahul.LAPTOP-IB8N85JR\Desktop\Training\Python\Python Evening 12\Scratchpads\house_candidates.xlsx"
# )

# ----------------------------------

# import openpyxl

# path = r"C:\Users\rahul.LAPTOP-IB8N85JR\Desktop\Training\Python\Python Evening 12\Scratchpads\house_candidates.xlsx"
# wb = openpyxl.load_workbook(path)
# sh = wb.active
# # sh = wb["sheet2"]

# # Read
# for i in range(1, sh.max_row + 1):
#     for j in range(1, sh.max_column + 1):
#         print(sh.cell(row=i, column=j).value)


# -----------------------------------

# import docx
# from docx.enum.text import WD_ALIGN_PARAGRAPH
# from docx.shared import Inches

# doc = docx.Document()
# doc.add_heading("The REAL meaning of the computer programming", 0)
# doc.add_heading("The role of dolphins", level=2)

# para = doc.add_paragraph(
#     "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Reprehenderit iure rem tenetur nostrum cupiditate molestias ipsum repudiandae perferendis neque, quibusdam beatae impedit voluptas. Ex velit, veritatis molestias temporibus labore ea pariatur consequatur libero, explicabo est voluptate necessitatibus inventore assumenda cum odit quia atque fugit nihil harum eos. Necessitatibus nihil mollitia nulla! Sit sequi deserunt voluptas repudiandae illo distinctio ipsum voluptatem suscipit repellat corporis, autem, illum velit iure consequuntur nisi quia laudantium culpa. Amet delectus aut quos iusto ipsam similique hic ratione quod totam! Quidem, reprehenderit! Nostrum, voluptas soluta! Nobis fugit sunt deserunt necessitatibus mollitia, expedita sint esse amet laboriosam sed."
# )

# para2 = para.add_run(
#     "\n\nLorem ipsum dolor sit amet consectetur adipisicing elit. Exercitationem, dicta? Voluptates perspiciatis ducimus doloribus est quis laboriosam asperiores dolorem, accusamus, maxime quam corrupti, non quidem voluptatibus repellat quae. Explicabo, culpa."
# )

# para2.bold = True

# doc.add_heading("New Heading", 4)
# para3 = doc.add_paragraph(
#     "Reprehenderit iure rem tenetur nostrum cupiditate molestias ipsum repudiandae perferendis neque, quibusdam beatae impedit voluptas. Ex velit, veritatis molestias temporibus labore ea pariatur consequatur libero, explicabo est voluptate necessitatibus inventore assumenda cum odit quia atque fugit nihil harum eos. Necessitatibus nihil mollitia nulla! Sit sequi deserunt voluptas repudiandae illo distinctio ipsum voluptatem suscipit repellat corporis, autem, illum velit iure consequuntur nisi quia laudantium culpa. Amet delectus aut quos iusto ipsam similique hic ratione quod totam! Quidem, reprehenderit! Nostrum, voluptas soluta! Nobis fugit sunt deserunt necessitatibus mollitia, expedita sint esse amet laboriosam sed."
# )

# para3.alignment = WD_ALIGN_PARAGRAPH.RIGHT

# doc.add_page_break()

# doc.add_heading("New Page Heading")

# doc.add_picture("bike.jpg", width=Inches(4.0))

# # para2.alignment =

# doc.save(
#     r"C:\Users\rahul.LAPTOP-IB8N85JR\Desktop\Training\Python\Python Evening 12\Scratchpads\sample_doc.docx",
# )


# ------------------------
# from pywinauto.application import Application
# import pywinauto
# from time import sleep


# app = Application(backend="uia").start("notepad.exe")
# app.UntitledNotepad.menu_select("Help->About Notepad")


# # print(pywinauto.handleprops.is_toplevel_window(app.top_window()))
# # sleep(2)
# top_window = app.top_window()
# top_window.OK.click()

# # top_window.print_control_identifiers()

# app.UntitledNotepad.Edit.type_keys("Hello Human!", with_spaces=True)
# app.UntitledNotepad.menu_select("File->Save")
# save_window = app.UntitledNotepad.child_window(title_re="Save As")
# # save_window.print_control_identifiers()
# save_window.ComboBox.type_keys("skynet2.txt")
# save_window.Save.click()


# ------------------
import pyautogui
from pywinauto.application import Application

app = Application(backend="uia").start("mspaint.exe")
print(pyautogui.size())

# pyautogui.moveTo(300, 400, duration=1)

distance = 200

while distance > 0:
    pyautogui.dragRel(distance, 0, duration=0.2)
    distance = distance - 5
    pyautogui.dragRel(0, distance, duration=0.2)
    pyautogui.dragRel(-distance, 0, duration=0.2)
    distance = distance - 5
    pyautogui.dragRel(0, -distance, duration=0.2)

# pyautogui.screenshot("screen.png")

Scratchpad #36

import sqlite3
from csv import reader

# create connection
conn = sqlite3.connect("pystudents.db")

# initialize cursor oject
c = conn.cursor()

# # create table
# c.execute("CREATE TABLE users (username TEXT, password TEXT);")

# person = ["john", "doe", 25]

# query = "INSERT INTO students VALUES (?,?,?)"
# c.execute(query, person)

# c.execute(
#     "CREATE TABLE elections (district TEXT, candidate TEXT, party TEXT, total_votes INTEGER, won TEXT);"
# )

with open("house_candidate.csv") as file:
    data = []
    csv_reader = reader(file)
    for row in csv_reader:
        data.append(row)

    query = "INSERT INTO elections VALUES (?,?,?,?,?);"
    # c.executemany(query, data)

    for row in data:
        c.execute(query, row)
        print(f"{row[1]} has been added to the database.")


conn.commit()
conn.close()

Scratchpad #37 and #38

from selenium import webdriver
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(3)

# Search the element on the page and return it
search_box = browser.find_element_by_xpath(
    "/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input"
)
search_box.send_keys("tool schism", Keys.ENTER)
sleep(3)

# song = browser.find_element_by_partial_link_text('Schism')
# sleep(1)
# song.click()

browser.find_element_by_partial_link_text("Schism").click()
sleep(15)

next_song = browser.find_element_by_partial_link_text("Vicarious")
sleep(1)

if next_song:
    next_song.click()
else:
    browser.get("https://www.youtube.com/watch?v=dQw4w9WgXcQ")

sleep(15)

browser.get("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
sleep(10)
browser.close()


# ---------------------


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep

browser = webdriver.Chrome("chromedriver.exe")

browser.maximize_window()
browser.get("https://www.irctc.co.in/nget/train-search")
sleep(3)

alert_btn = browser.find_element_by_xpath(
    "/html/body/app-root/app-home/div[1]/app-header/p-dialog[2]/div/div[2]/div/form/div[2]/button"
)
sleep(3)
alert_btn.click()

Scratchpad #43, #44

# Selenium

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep

browser = webdriver.Chrome("chromedriver.exe")
browser.maximize_window()

browser.get("https://web.whatsapp.com/")
sleep(10)

search_input = browser.find_element_by_xpath('/html/body/div[1]/div/div/div[3]/div/div[1]/div/label/div/div[2]')
search_input.click()
search_input.send_keys("PYTHON EVE RS 12/10/20", Keys.ENTER)

i = 0
while i < 20:
    msg_box = browser.find_element_by_xpath('/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]')
    msg_box.click()
    msg_box.send_keys("SENT FROM MY SELENIUM SCRIPT")

    send_btn = browser.find_element_by_xpath('/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div[3]/button')
    send_btn.click()
    i += 1

sleep(10)
browser.close()

# Decorators
from time import time

def speed_test(fn):
    def wrapper(*args, **kwargs):
        start_time = time()
        print(f"Executing {fn.__name__}")
        result = fn(*args, **kwargs)
        end_time = time()
        print(f"Time Elasped: {end_time - start_time}")
        return result
    return wrapper


@speed_test
def sum_nums_gen():
    return sum(x for x in range(10000000))

@speed_test
def sum_nums_list():
    return sum([x for x in range(10000000)])


print(sum_nums_gen())
print(sum_nums_list())


# # Decorator 2

def ensure_first_arg(val):
    def inner(fn):
        def wrapper(*args, **kwargs):
            if args and args[0] != val:
                print(f"First arg needs to be {val}")
            else:
                return fn(*args, **kwargs)
        return wrapper
    return inner


# With the decorator syntax
@ensure_first_arg("Desh Drohi")
def fav_movies(*movies):
    print(movies)

# Without the decorator syntax style
# nulla = ensure_first_arg("Desh Drohi")
# nulla2 = nulla(fav_movies)
# # print(nulla2)
# nulla2("Lagaan", "Rang De Basanti")


fav_movies("Desh Drohi", "Lagaan", "Rang De Basanti")

# 1. Write a function which will accepts a list and returns
# the number of times a number is followed by a larger number
# across the entire list

# find_larger_numbers([1,5,2,7,10,43,1,0])

# 2. Write a function which accepts a (NxN) list of lists
# and sums the two main diagonals in the array.
# the one from the upper left to the lower right, and the one
# from the upper right to the lower left

# myList = [
#     [1,2,3,4],
#     [4,5,6,4],
#     [7,8,9,4],
#     [7,8,9,4]
# ]