Loading...
# # The line below prints something on the screen
# print(100 + 23) # hello world
# print(100 - 23)
# print(2 + 3 / 4) # asdklasjkdl
# Snake casing
# first_second
# first_name
# gst_amount
# firstName
# gstAmount
# GstAmountNextWord
# gst-amount
x = 50
current_year = 2020
average_salary_of_a_python_developer = 50000
print(current_year + x)
# http://labs.rstforum.net/registration
# # name = "John Doe"
# # name = first_name.upper()
# # name.lower().find("doe")
# # name.find("John").upper()
# text = "Lorem ipsum dolor, sit amet consectetur adipisicing elit. Consectetur vitae pariatur libero fuga quos magnam neque distinctio rerum, ducimus, ipsam earum provident quibusdam similique unde facere explicabo odit minus, cupiditate possimus quia! Earum amet fugit alias error adipisci praesentium, ullam, laboriosam odit quia nihil ipsum inventore! Aspernatur illo magni amet architecto repellat. Ipsam ratione quia sit atque libero, veritatis totam blanditiis qui in molestias vero quos quae expedita nisi fugit voluptate molestiae corrupti illo itaque labore! Reiciendis et maxime sed temporibus unde quaerat iste! Consequatur atque delectus nobis ex earum tenetur voluptatibus non cumque. Provident iusto esse laborum quidem quaerat fugiat, tenetur est enim dolore, aut ratione soluta repellat eos quo consequatur, perferendis rem architecto? Dicta a, obcaecati rem minus quo sequi molestias! Id nobis possimus dolorum impedit? Aspernatur aliquid molestiae ratione magnam culpa deserunt optio ducimus consequuntur odio. Culpa voluptatibus, quos eum commodi inventore eveniet dignissimos deserunt aperiam incidunt distinctio corrupti consectetur ipsam minus. Aut voluptatem eaque sequi voluptate, facere in odio sapiente nulla cupiditate accusamus corporis labore fuga ab consectetur possimus magni dicta similique. Cumque nam magni, vero ex quisquam dignissimos, aperiam asperiores adipisci, quae architecto autem. Recusandae ipsa inventore temporibus accusamus aliquid praesentium natus esse quis autem?"
# print(text.find("ipsa"))
# print("Amount of US Dollars you want to convert")
# usd = input()
# usd = input("Amount of US Dollars you want to convert: ")
# usd = float(usd)
# inr = usd * 75.65
# # print(f"You entered {usd}")
# # print(type(usd))
# print(f"{usd} USD is equal to {int(inr)} INR")
# name = input("Please enter someone famous: ")
# if name.lower() == "Mark Zuckerberg".lower():
# print("Facebook")
# elif name == "Jack Dorsey":
# print("Twitter")
# elif name == "Sundar Pichai":
# print("Google")
# else:
# print("Someone I don't know")
name = ""
if name:
print(f"Hello {name}")
# age = input("How old are you? ")
# if age:
# if int(age) >= 18 and int(age) < 21:
# print("You are allowed to enter but not drink")
# elif int(age) >= 21 and int(age) < 65:
# print("You can enter and drink")
# elif int(age) >= 65:
# print("Drinks are free")
# else:
# print("You are not allowed")
# else:
# print("Please enter a valid age!")
# if int(age) >= 18:
# print("You are allowed to enter but not drink")
# elif int(age) >= 21:
# print("You can enter and drink")
# elif int(age) >= 65:
# print("Drinks are free")
# else:
# print("You are not allowed")
# if age:
# age = int(age)
# if age >= 65:
# print("Drinks are free")
# elif age >= 21:
# print("You can enter and drink")
# elif age >= 18:
# print("You are allowed to enter but not drink")
# else:
# print("You are not allowed")
# else:
# print("Please enter a valid age")
# player1 = input("Please enter your choice: ")
# player2 = input("Please enter your choice: ")
# if (
# (player1 == "stone" and player2 == "scissors")
# or (player1 == "paper" and player2 == "stone")
# or (player1 == "scissors" and player2 == "paper")
# ):
# print("Player 1 wins")
# elif (
# (player2 == "stone" and player1 == "scissors")
# or (player2 == "paper" and player1 == "stone")
# or (player2 == "scissors" and player1 == "paper")
# ):
# print("Player 2 wins")
# elif player1 == player2:
# print("It's a tie")
# else:
# print("Something went wrong")
# if player1 == player2:
# print("It's a tie")
# elif player1 == "stone":
# if player2 == "scissors":
# print("Player 1 wins")
# elif player2 == "paper":
# print("Player 2 wins")
# elif player1 == "paper":
# if player2 == "stone":
# print("Player 1 wins")
# elif player2 == "scissors":
# print("Player 2 wins")
# elif player1 == "scissors":
# if player2 == "paper":
# print("Player 1 wins")
# elif player2 == "stone":
# print("Player 2 wins")
# else:
# print("Something went wrong")
# for item in "hello world":
# print(item)
# for num in range(10, 99):
# print(num)
# my_range = range(-10, 11)
# for number in my_range:
# print(number ** 2)
# for num in range(0, 10):
# print(num)
# for num in range(1,21):
# password = input("Please enter your password: ")
# while password != "balony1":
# print("Wrong password!")
# password = input("Please enter your password again: ")
# for num in range(1, 11):
# print(num)
# count = 1
# while count < 11:
# print(count)
# count += 1
# for num in range(1, 5):
# for num2 in range(1, 5):
# print(num, num2)
# player1 = input("Please enter your choice: ")
# player2 = input("Please enter your choice: ")
# if player1 == player2:
# print("It's a tie")
# elif player1 == "stone":
# if player2 == "scissors":
# print("Player 1 wins")
# elif player2 == "paper":
# print("Player 2 wins")
# elif player1 == "paper":
# if player2 == "stone":
# print("Player 1 wins")
# elif player2 == "scissors":
# print("Player 2 wins")
# elif player1 == "scissors":
# if player2 == "paper":
# print("Player 1 wins")
# elif player2 == "stone":
# print("Player 2 wins")
# else:
# print("Something went wrong")
# count = 1
# secret_password = input("Please enter your password: ")
# while secret_password != "balony1":
# count += 1
# if count > 3:
# break
# secret_password = input("Incorrect! Enter password again: ")
# while True:
# if secret_password == "balony1":
# break
# secret_password = input("Please enter your password: ")
# print(count)
# from random import randint
# start_range = int(input("Enter the starting range: "))
# end_range = int(input("Enter the ending range: "))
# random_number = randint(start_range, end_range)
# random_number = randint(1, 10)
# while True:
# while True:
# guess = input("Pick a number between 1 and 10: ")
# if guess:
# guess = int(guess)
# break
# else:
# print("Please enter a valid number: ")
# if guess < random_number:
# print("TOO LOW")
# elif guess > random_number:
# print("TOO HIGH")
# else:
# print("YOU WON!")
# print(guess)
# play_again = input("Do you want to play again? (y/n): ")
# if play_again.lower() == "y":
# random_number = randint(1, 10)
# guess = None
# else:
# print("Thank you for playing")
# break
# tasks = "Buy milk|Pay bills|another task"
# tasks = ["Buy milk", "Pay bills", "Another task"]
# print(tasks[0])
# tasks = []
# while True:
# task = input("Please enter your task (q to quit): ")
# if task == "":
# print("Please enter a valid task")
# elif task == "q":
# break
# else:
# tasks.append(task)
# print("Here are you tasks: ")
# for task in tasks:
# print(task)
# nums_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# # print(len(nums_list))
# print(nums_list[0][-1])
# nums_list = [["jane", "john", "jack"], 2, 3, 4, 4, 4, 4, 4, 4, 4, 4]
# for item in nums_list:
# print(item)
names = ["jane", "john", "james", "jack", "jill", "jonathan"]
# print(nums[3])
i = 0
while i < len(names):
print(f"{i + 1} - {names[i]}")
i += 1
# count = 0
# for name in names:
# print(name)
# count += 1
# # my_list = [1, 2, 2, 3, 4, 55, 23, 3, 2, 65, 2]
# # print(my_list.count(2))
# # names = ["adam", "chris", "dhruv", "john", "yash", "zack", "zubair", "xarvis", "wu"]
# # upper_names = [name.upper() + "aaa" for name in names]
# # print(upper_names)
# # upper_names = []
# # for name in names:
# # upper_names.append(name.upper())
# # print(upper_names)
# names = ["adam", "chris", "dhruv", "john", "yash", "zack", "zubair", "xarvis", "wu"]
# [name for name in names]
# nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# for item in nested_list:
# for num in item:
# print(num)
# [lst for lst in nested_list]
# var = "JOHN"
# product = ["iPhone", "Apple", "Some description", 100000, 250]
# products = [
# ["iPhone 12", "Apple", "Some description", 100000, 250],
# ["One Plus Nord", "One Plus", "Some description", 40000, 250],
# ["iPhone 13", "Apple", "Some description", 250, 40000],
# ]
# for prod in products:
# print(f"Product Name: {prod[0]}")
# print(f"Product Brand: {prod[1]}")
# print(f"Product Description: {prod[2]}")
# print(f"Product Price: {prod[3]}")
# print(f"Product Stock: {prod[4]}")
# print("\n")
product = ["iPhone 12", "Apple", "Some description", 100000, 250]
product = {
"name": "iPhone 12",
"description": "Some description",
"stock": 250,
"price": 10000,
"brand": "Apple",
}
products = [
{
"name": "iPhone 12",
"description": "Some description",
"stock": 250,
"price": 10000,
"brand": "Apple",
},
{
"description": "Some description",
"name": "iPhone 12",
"price": 10000,
"brand": "Apple",
"stock": 250,
},
]
print(product["name"])
print(product["brand"])
print(product["description"])
print(product["price"])
print(product["stock"])
# names = ["john", "jack", "jane"]
# profile = {"first_name": "John", "last_name": "Doe", "age": 25}
# name_dict = {0: "John", 1: "Doe", 2: "age"}
# print(names_d)
# song = {
# "name": "Song 1",
# "album": "Some album",
# "artists": ["John", "Jane"],
# "metadata": {"id": 2143324, "other": True},
# }
# print(song["metadata"]["other"])
# for item in song:
# print(item)
# names = ["john", "jack", "jane"]
# i = 0
# while i < len(names):
# print(names[i])
# i += 1
# profile = {"first_name": "John", "last_name": "Doe", "age": 25}
# for value in profile.values():
# print(value)
# for key in profile.keys():
# print(key)
# profile["first_name"]
# for key in profile:
# print(profile[key])
# print(profile.keys())
# print(profile.values())
# print(profile.items())
# for item in profile.items():
# print(item)
# for key, value in profile.items():
# print(f"The value of {key} is {value}")
# for k, v in profile.items():
# print(f"The value of {k} is {v}")
# song = {
# "name": "Sober",
# "artist": "Tool",
# "album": "Undertow",
# }
# print(song["name"])
# print(song.get("name"))
# print(song["length"])
# print(song.get("length"))
# print("Hello World")
# for char in "John Doe":
# print(char)
# countries = (("IN", "India"), ("UK", "United Kingdom"), ("AF", "Afghanistan"))
# print(countries)
# location = {
# (19.8901232, 72.123123): "Mumbai Office",
# (16.8901232, 72.123123): "San Francisco Office",
# (19.8901232, 72.123123): "Dubai Office",
# }
# def greet():
# print("Hello World")
# print("Hello, Jack")
# print("How are you")
#
#
# greet()
# greet()
# greet()
# def greet():
# print("Hello World")
# greet()
# score = 100
# print(type(score))
# type("Hello World")
# "hello".upper()
# print(None)
# def greet():
# print("Hello World")
# score = 100 + 34
# return score
# print(greet())
# print(greet())
def print_num():
for num in range(10):
return "john"
print(num)
print(print_num())
# def greet():
# return "hello world"
# print(greet())
# print(greet())
# print(greet())
# from random import random
# def flip_coin():
# if random() > 0.5:
# return "HEADS"
# else:
# return "TAILS"
# print(flip_coin())
# print(flip_coin())
# print(flip_coin())
# user = "John Doe"
# user = "John"
# def greet(user):
# return f"Hello {user}"
# print(greet("John Doe"))
# print(greet("Jane"))
# def add(num1, num2):
# return num1 + num2
# print(add(10, 4))
# print(add(-54, 32))
# def say_name(first, last):
# return f"{first} {last}".upper()
# print(say_name("Doe", "John"))
# def add(x, y):
# return x + y
# def sub(x, y):
# return x - y
# def mul(x, y):
# return x * y
# def math(x, y, fn):
# return fn(x, y)
# print(math(10, 5))
# add(10) ERROR
# def sum_odd_numbers(numbers):
# total = 0
# for num in numbers:
# if num % 2 == 1:
# total += num
# return total
# def is_odd_number(number):
# if number % 2 == 1:
# return True
# return False
# print(sum_odd_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
# print(is_odd_number(10))
# def greet(first, last, message):
# return f"{message}, {first} {last}"
# print(greet(last="Doe", message="Hello", first="Jack"))
# def add(x=0, y=0):
# return x + y
# print(add(10, 45))
# print(add())
# def greet(last=0, first, message="Hi"):
# return f"{message}, {first} {last}"
# print(greet("Jack", "Doe", "hello"))
# def greet(first="john", last="doe", age=0, message="Hi"):
# return f"{message}, {first} {last}. You are {age} years old."
# print(greet("John", "Doe", "young", "Hi"))
# name = "Shahrukh"
# type = "Human"
# def greet():
# # name = "John"
# # type = "Animal"
# print(type)
# # print(name)
# greet()
# age = 25
# def greet(first_name, last_name):
# def make_message():
# age = 25
# return f"My name is {first_name} {last_name}. I am {age} years old."
# message = make_message()
# return message
# first_name = input("Please enter your first name: ")
# last_name = input("Please enter your last name: ")
# # print(greet("John", "Doe"))
# print(greet(first_name, last_name))
name = "Steve Rogers"
def func(name):
# global name
name += " is captain America"
return name
# print(name)
name = func(name)
# name = new_str
print(name)
# def outer():
# count = 10
# def inner():
# nonlocal count
# count += 10
# return count
# return inner()
# print(outer())
# def greet(name, message="Hi"):
# """Function that will print a greeting
# @param name: str
# @param message: str (default="Hi")
# @returns str
# eg: greet("John Doe", "Hello")
# """
# name = name.upper()
# return f"{message}, {name}"
# # greet("John Doe", "Hello, How are you")
# # print(greet.__doc__)
# print(help(greet))
# def add(*nums):
# total = 0
# for num in nums:
# total += num
# return total
# def add2(a, b):
# return a + b
# print(add2(10, 30, 20, 4))
# print(add(10, 50, 2, 32, 4))
# def print_names(owner, customer, *others):
# print(owner)
# print(customer)
# print(others)
# print_names(
# "Clint", "Bruce", "Tony", "Thor", "Warmachine", "Bruce Wayne", "Peter Parker"
# )
# def user_details(*args, **kwargs):
# # print("User details:\n")
# # for k, v in kwargs.items():
# # print(f"{k}: {v}")
# print(args)
# print(kwargs)
# # user_details(name="Peter", age=35, city="Manhattan")
# user_details("Peter", 35, city="Manhattan")
# def show_info(a, b, *args, role="moderator", **kwargs):
# return [a, b, args, role, kwargs]
# print(
# show_info(
# 1, 2, 3, 4, 5, 6, 7, role="Leader", first_name="John", last_name="Manhunter"
# )
# )
# def add(*nums):
# total = 0
# for num in nums:
# total += num
# print(total)
# # add(10, 4, 5, 6, 7, 82, 123, 3)
# nums = [12, 34, 456, 56, 5, 32, 1234, 5]
# add(*nums)
# def names(person1, person2):
# print(person1, person2)
# people = ["John", "Jack"]
# names(*people)
# def say_name(first, last):
# print(f"My name is {first} {last}.")
# # say_name(first="John", last="Doe")
# name = {"first": "Robert", "last": "Moore"}
# say_name(**name)
# def greet(name):
# return f"Hello, {name}"
# def add(a, b):
# return a + b
# greet2 = lambda name: f"Hello, {name}"
# print(greet2("Jack"))
# # var = add
# print(var(10, 2))
def math(a, b, fn):
return fn(a, b)
# math = lambda a, b, fn: fn(a, b)
# def add(a, b):
# return a + b
# print(math(10, 20, add))
# print(math(10, 20, lambda a, b: a - b))
# print(math(10, 20, lambda a, b: f"a is {a}, b is {b}"))
# people = ["peter", "tony", "eddie", "thor", "steven"]
# # uppercased_people = [name.upper() for name in people]
# # print(uppercased_people)
# uppercased_people = map(lambda name: name.upper(), people)
# print(list(uppercased_people))
# my_list = [1, 2, 3, 4]
# evens = filter(lambda num: num % 2 == 0, my_list)
# print(list(evens))
names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"]
print(
list(
map(
lambda name: f"The one who wins is {name}",
filter(lambda name: len(name) < 5, names),
)
)
)
# nums = [1, 2, 3, 6, 7, 32, 12]
# products = [
# {"name": "Apple iPhone", "price": 100000},
# {"name": "One Plus", "price": 50000},
# {"name": "Huawei Honor", "price": 20000},
# {"name": ""},
# {"name": "Xiaomi Mi 11 Pro", "price": 60000},
# ]
# # print(all(products))
# if all(products):
# for prod in products:
# print(f"{prod['name']} costs {prod['price']}")
# else:
# print("Issues with the data. Please check.")
# people = ["John", "Jack", "James", "Jason", "Jane", "Jacob"]
# # print(all())
# print(all([name[0] == "J" for name in people]))
# products = [
# {"name": "Apple iPhone", "price": 100000},
# {"name": "One Plus", "price": 50000},
# {"name": "Huawei Honor", "price": 20000},
# {},
# {"name": "Xiaomi Mi 11 Pro", "price": 60000},
# ]
# print(any(products))
# password = input("Please enter a password: ")
# if len(password) < 6:
# print("Password is too short")
# else:
# print("Good password")
# if len("hello"):
# pass
# def greet():
# pass
# https://docs.python.org/3/library/exceptions.html
# def colorize(text, color):
# colors = ("red", "yellow", "blue", "green", "purple")
# if type(text) is not str:
# raise TypeError("text arg should be a str")
# if type(color) is not str:
# raise TypeError("color arg should be a str")
# if color not in colors:
# raise ValueError("color is invalid")
# # some logic
# print(f"Printed {text} in {color}")
# # colorize("hello john doe", "red")
# # colorize("hello john doe", "yellow")
# colorize(1000, "yellow")
# hello
# try:
# hello
# except:
# print("ERROR PROBLEM. FIX IT.")
# cities = ["mumbai", "pune", "delhi", "bangalore", "chennai"]
# try:
# cities[10]
# except:
# print("Fix")
# def divide(a, b):
# try:
# return a / b
# except ZeroDivisionError:
# return "Please check your args"
# def divide(a, b):
# try:
# return a / b
# except (ZeroDivisionError, TypeError):
# return "Please check your args"
# def divide(a, b):
# try:
# return a / b
# except (ZeroDivisionError, TypeError) as err:
# print(err)
# return "Please check your args"
# def divide(a, b):
# try:
# return a / b
# except Exception as err:
# print(err)
# return "Please check your args"
# # print(divide(10, "sda"))
# print(divide(10))
import pdb
def divide(a, b):
try:
pdb.set_trace() # breakpoint
result = a / b # attempt
except Exception as err:
print(err)
else:
return result
finally:
print("I will always run!")
# divide(10, 0)
print(divide(10, 3))
# https://docs.python.org/3/py-modindex.html
# import random
# # print(random.choice(["Core i9", "Ryzen 9", "Core i7", "Ryzen 7"]))
# # print(random.randint(100, 200))
# random = "hello"
# lst = ["Core i9", "Ryzen 9", "Core i7", "Ryzen 7"]
# random.shuffle(lst)
# print(lst)
# # import random as helloworld
# import random as r
# print(r.choice(["Ryzen 7", "Ryzen 9", "Core i7", "Core i9"]))
# # from random import randint, choice, shuffle
# from random import randint as ri, choice as c, shuffle
# # from random import *
# print(c(["Core i9", "Ryzen 9", "Core i7", "Ryzen 7"]))
# print(ri(100, 200))
# class User:
# pass
# # user2 = "john"
# user1 = User()
# user2 = User()
# user3 = User()
# # print(type(user1))
# print(user1)
# print(user2)
# print(user3)
# user1.deposit()
from random import shuffle as sh
def create_deck():
vals = "2,3,4,5,6,7,8,9,10,A,K,Q,J"
suits = ["spades", "hearts", "diamonds", "clubs"]
deck = []
for val in vals.split(","):
for suit in suits:
deck.append({"val": val, "suit": suit})
return deck
def shuffle(deck):
return sh(deck)
def draw_card(deck, drawn_cards):
card = deck.pop()
drawn_cards.append(card)
return card
def draw_multiple(no, deck, drawn_cards):
for time in range(no):
draw_card(deck, drawn_cards)
def initialize_deck():
deck = create_deck()
drawn_cards = []
return {"deck": deck, "hand": drawn_cards}
# deck1 = initialize_deck()
# print(deck1["hand"])
class Deck:
def __init__(self):
self.deck = create_deck()
self.hand = []
def draw_card(self):
card = self.deck.pop()
self.hand.append(card)
return card
deck1 = Deck()
deck1.draw_card()
print(deck1.hand)
# deck1 = create_deck()
# cards_in_hand = []
# shuffle(deck1)
# # draw_multiple(13, deck1, cards_in_hand)
# # draw_card(deck1, cards_in_hand)
# # print(cards_in_hand)
# print(deck1)
# class Deck:
# def __init__(self, )
# class User:
# def __init__(self, firstName, lastName):
# self.firstName = firstName
# self.lastName = lastName
# def print_name(self):
# print(self.firstName, self.lastName)
# user1 = User("John", "Doe")
# user2 = User("Jack", "Ma")
# user3 = User("Jane", "Smith")
# user1.print_name()
# user2.print_name()
# print(user1.firstName, user1.lastName)
# print(user2.firstName, user2.lastName)
# print(user3.firstName, user3.lastName)
# from random import shuffle as sh
# class Deck:
# def __init__(self):
# self.deck = []
# self.hand = []
# def create_deck(self):
# vals = "2,3,4,5,6,7,8,9,10,A,K,Q,J"
# suits = ["spades", "hearts", "diamonds", "clubs"]
# for val in vals.split(","):
# for suit in suits:
# self.deck.append({"val": val, "suit": suit})
# return self.deck
# def shuffle(self):
# return sh(self.deck)
# def draw_card(self):
# card = self.deck.pop()
# self.hand.append(card)
# return card
# def draw_multiple(self, no):
# for time in range(no):
# self.draw_card()
# deck1 = Deck()
# deck1.create_deck()
# deck1.shuffle()
# deck1.draw_card()
# deck1.draw_multiple(5)
# print(deck1.hand)
# class User:
# nationality = "Indian"
# def __init__(self, first_name, last_name, age):
# self.first_name = first_name
# self.last_name = last_name
# self.age = age
# self.city = "Mumbai"
# def print_details(self):
# print(f"First Name: {self.first_name}\nLast Name: {self.last_name}")
# user1 = User("John", "Doe", 25)
# user2 = User("Jane", "Doe", 27)
# user3 = User("Jack", "Ma", 45)
# print(user1.nationality)
# print(user2.nationality)
# print(User.nationality)
# user1.print_details()
# user2.print_details()
# print_details(user1)
# user3.print_details()
# print(user2._User__age)
# print(user1.get_age())
class User:
active = 0
total = 0
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
self.city = "Mumbai"
User.total += 1
@classmethod
def get_active_users(cls):
return cls.active
def print_details(self):
print(f"First Name: {self.first}\nLast Name: {self.last}")
def login(self):
print(f"{self.first} logged in")
User.active += 1
def logout(self):
print(f"{self.first} logged out")
User.active -= 1
user1 = User("John", "Doe", 25)
user2 = User("Jack", "Ma", 46)
user3 = User("Jane", "Ma", 46)
# user3.login()
# user2.login()
# # print("Active Users: ", User.active)
# # print("Total Users", User.total)
# user2.logout()
# # print("Active Users: ", User.active)
# print(User.get_active_users())
# print(user2.get_active_users())
# from random import random as r
# class Math:
# @classmethod
# def add(cls, a, b):
# return a + b
# @classmethod
# def sub(cls, a, b):
# return a - b
# @classmethod
# def random(cls):
# return r()
# print(Math.add(10, 5))
# print(Math.sub(10, 5))
# print(Math.random())
# # class User:
# # active = 0
# # total = 0
# # def __init__(self, first, last, age):
# # self.first = first
# # self.last = last
# # self.age = age
# # self.city = "Mumbai"
# # User.total += 1
# # def __repr__(self):
# # # return f"{self.first} {self.last}"
# # return f"User({self.first}, {self.last}, {self.age})"
# # @classmethod
# # def get_active_users(cls):
# # return cls.active
# # def print_details(self):
# # print(f"First Name: {self.first}\nLast Name: {self.last}")
# # def login(self):
# # print(f"{self.first} logged in")
# # User.active += 1
# # def logout(self):
# # print(f"{self.first} logged out")
# # User.active -= 1
# # # user1 = User("John", "Doe", 25)
# # # user2 = User("Jack", "Ma", 46)
# # # user3 = User("Jane", "Ma", 46)
# # # print(user1)
# # # print(user2)
# # # print(user3)
# class User:
# def __init__(self, name, age, email, passwd):
# self.name = name
# self._age = age
# self.email = email
# self.passwd = passwd
# def __repr__(self):
# return f"User({self.name}, {self._age}, {self.email}, {self.passwd})"
# def login(self, passwd):
# if passwd == self.passwd:
# print("Hello")
# else:
# print("Not authorized")
# @property
# def age(self):
# return self._age
# @age.setter
# def age(self, new_age):
# if new_age > 100:
# raise ValueError("Buzz off")
# else:
# self._age = new_age
# # def get_age(self):
# # return self._age
# # def set_age(self, new_age):
# # self._age = new_age
# # return new_age
# class Mod(User):
# def __init__(self, name, age, email, passwd, phone):
# super().__init__(name, age, email, passwd)
# self.phone = phone
# def edit_profile(self, name, age, email, passwd):
# if name:
# self.name = name
# if age:
# self._age = age
# if email:
# self.email = email
# if passwd:
# self.passwd = passwd
# print("Profile updated successfully")
# user1 = User("John Doe", 25, "john@gmail.com", "john@123")
# user2 = Mod("Jack Doe", 27, "jack@gmail.com", "jack@123", "+91 987878234")
# # user1.login("john@123")
# # user2.login("helloworld")
# # print(user2)
# # user2.edit_profile(None, 28, "jack@protonmail.com", None)
# # print(user2)
# # user1.name = "James Smith"
# # print(user1.get_age())
# # user1.set_age(33)
# # print(user1)
# # user1.age = 3000
# # # print(user1.age)
# print(user2.phone)
# class Animal:
# def walk(self):
# print("Walking")
# def speak(self):
# print("alndjsandjsandla")
# class Human:
# def speak(self):
# print("Talking")
# class Mutant(Human, Animal):
# def fight(self):
# print("Fighting")
# # print(help(Mutant))
# dog = Animal()
# john = Human()
# logan = Mutant()
# # dog.walk()
# # john.speak()
# logan.speak()
# # logan.walk()
# # logan.fight()
# class User:
# def login(self):
# raise NotImplementedError("Subclass needs to implement this")
# def logout(self):
# raise NotImplementedError("Subclass needs to implement this")
# def update_profile(self):
# raise NotImplementedError("Subclass needs to implement this")
# class Customer(User):
# pass
# cus1 = Customer()
# cus1.login()
class Human:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return self.name
def __len__(self):
return self.age
def __add__(self, other):
return Human("new human", "0")
def __mul__(self, other):
pass
john = Human("John Doe", 25)
jane = Human("Jane Doe", 26)
# print(john.name, john.age)
# print(len(john))
newborn = john + jane
print(newborn)
# # def custom_for(iterable):
# # iterator = iter(iterable)
# # while True:
# # try:
# # print(next(iterator))
# # except StopIteration:
# # break
# # for iterator in iterable:
# # ...
# # custom_for([12, 4, 56, 73, 2346])
# # custom_for("Hello")
# # def custom_map(func, iterable):
# # iterator = iter(iterable)
# # while True:
# # try:
# # i = next(iterator)
# # except StopIteration:
# # break
# # else:
# # func(i)
# # custom_map(lambda char: print(char), "Hello World")
# 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
# # c = Counter(5, 10)
# # next(c) 5
# # next(c) 6
# for item in Counter(1, 10, 2):
# print(item)
# # print(Counter(0, 10))
# # LAZY
# def count_to_g(max):
# count = 1
# while count <= max:
# yield count
# count += 1
# counter = count_to_g(10)
# # print(list(counter))
# for num in counter:
# print(num)
# def count_to_r(max):
# result = []
# count = 1
# while count <= max:
# result.append(count)
# count += 1
# return result
# counter = count_to_r(10)
# # print(counter)
# for num in counter:
# print(num)
# def fib_list(max):
# nums = []
# a, b = 0, 1
# while len(nums) < max:
# nums.append(b)
# a, b = b, a + b
# return nums
# 0, 1, 1, 2, 3, 5, 8, 13,
# result = fib_list(1000000)
# print(sum(result))
# for num in result:
# print(num)
# def fib_gen(max):
# a, b = 0, 1
# count = 0
# while count < max:
# a, b = b, a + b
# yield a
# count += 1
# result = fib_gen(10)
# print(result)
# print(next(result))
# print(next(result))
# print(next(result))
# print(next(result))
# print(next(result))
# print(sum(result))
# from time import time
# gen_start_time = time()
# print(sum(num for num in range(100000000)))
# gen_stop_time = time() - gen_start_time
# list_start_time = time()
# print(sum([num for num in range(100000000)]))
# list_stop_time = time() - list_start_time
# print(f"generator time taken: {gen_stop_time}\nlist comp time taken: {list_stop_time}")
# def add(a, b):
# return a + b
# def math(a, b, fn):
# return fn(a, b)
# math(10, 5, add)
# math(10, 5, lambda a, b: a - b)
import random
# def greet(person):
# def get_mood():
# mood = ["Hey", "What!", "What the hell do you want!", "Get lost!"]
# msg = random.choice(mood) # import random
# return msg
# result = f"{get_mood()} {person}"
# return result
# print(greet("John"))
# def make_greet_func(person):
# def make_message():
# msg = random.choice(
# ["Hello", "What!", "What the heck do you want!", "Get lost!"]
# )
# return f"{msg} {person}"
# return make_message
# greet_john = make_greet_func("john")
# greet_jack = make_greet_func("jack")
# print(greet_john())
# print(greet_jack())
# is_under_age = is_between(0, 18)
# can_enter = is_between(18, 21)
# can_drink = is_between(21, 65)
# free_drinks = is_between(65, 100)
def is_between(start, end):
def compare(num):
return num >= start and num < end
return compare
age = 12
if is_between(0, 18)(age):
print("Get out!")
# print(is_under_age(12))
# def sum(num, fn):
# total = 0
# for num in range(1, num + 1):
# total += fn(num)
# return total
# def square(n):
# return n * n
# print(sum(10, square))
# print(sum(10, lambda n: n ** 3))
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(name):
# def make_message():
# mood = ["Hey", "What!", "What the heck do you want!", "Get lost!"]
# msg = random.choice(mood)
# return f"{msg} {name}"
# return make_message
# john_greet = make_greet_func("John")
# print(john_greet())
# def stars(fn):
# def wrapper():
# print("*" * 10)
# fn()
# print("*" * 10)
# return wrapper
# def say_hello():
# print("Hello World")
# # ordinary_hello = say_hello
# # ordinary_hello()
# # say_hello()
# # new_hello = stars(say_hello)
# # new_hello()
# say_hello = stars(say_hello)
# say_hello()
# def stars(fn):
# def wrapper():
# print("*" * 10)
# fn()
# print("*" * 10)
# return wrapper
# @stars # say_hello = stars(say_hello)
# def say_hello():
# print("Hello World")
# say_hello()
# from functools import wraps
# def stars(fn):
# """Decorator -> decorators functions with 10
# stars on the top and the bottom"""
# @wraps(fn)
# def wrapper(*args, **kwargs):
# """Enhanced function that is returned from the decorator"""
# print("*" * 10)
# fn(*args, **kwargs)
# print("*" * 10)
# return wrapper
# @stars # say_hello = stars(say_hello)
# def say_hello(name):
# """This function says hello to some person"""
# print(f"Hello {name}")
# @stars
# def say_something(message, name):
# """Print some custom message to someone"""
# print(f"{message}, {name}")
# # say_hello("John")
# # say_something("hello", "john")
# print(say_hello.__doc__)
# print(say_hello.__name__)
# from functools import wraps
# from time import time
# def speed_test(fn):
# @wraps(fn) # wraps(wrapper)
# def wrapper(*args, **kwargs):
# start_time = time()
# result = fn(*args, **kwargs)
# end_time = time()
# print(f"Executing {fn.__name__}")
# print(f"Time Elapsed: {end_time - start_time}")
# return result
# return wrapper
# @speed_test # speed_test(sum_num_gen)
# def sum_num_gen():
# return sum(x for x in range(5000000))
# @speed_test
# def sum_num_list():
# return sum([x for x in range(5000000)])
# print(sum_num_gen())
# print(sum_num_list())
def enforce(*types):
def inner(fn):
def wrapper(*args, **kwargs):
new_args = []
for a, t in zip(args, types):
try:
new_args.append(t(a)) # "2" -> int("2")
except (ValueError, TypeError):
return "Something went wrong"
return fn(*new_args)
return wrapper
return inner
@enforce(str, int) # announce = enforce(str, int)(announce)
def announce(msg, times):
print((msg + "\n") * times)
# announce = enforce(str, int)
# announce = inner(announce)
# announce = wrapper
# announce = enforce(str, int)(announce)
# announce("Hello World", 4)
# announce(1000, 4)
announce(1000, "five")
# file = open("text.txt")
# # print(file)
# print(file.read())
# with open("text.txt", "r") as file:
# print(file.read())
# print(file.closed)
# print(file.closed)
# with open("text.txt", "w") as file:
# file.write("Hello World\n")
# file.write("Hello Universe\n")
# file.write("Hello Solar System\n")
# with open("helloworld.txt", "w") as file:
# file.write("I am John Wick\n")
# file.write("I am Neo.")
# with open("text.txt", "a") as file:
# file.seek(0)
# file.write("Hello World")
# with open("text.txt", "r+") as file:
# file.seek(0)
# file.write("Hello World")
# with open("text.txt", "r") as file:
# contents = file.read()
# with open("text_copy.txt", "w") as file:
# file.write(contents[::-1])
# search_and_replace("text.txt", "john", "jane")
# stats("text.txt")
# {"words": 0, "chars": 0, "lines": 0}
# from csv import reader, DictReader
# with open("test.csv") as file:
# csv_reader = reader(file)
# for row in csv_reader:
# if row[0] == "john":
# print(row)
# print(next(csv_reader))
# with open("test.csv") as file:
# csv_reader = DictReader(file)
# for row in csv_reader:
# print(row)
# from csv import writer
# with open("text.csv", "a") as file:
# csv_writer = writer(file)
# csv_writer.writerow(["Name", "Phone", "Email"])
# csv_writer.writerow(["Jack", "123213", "jane@gmail.com"])
# csv_writer.writerow(["Jane", "123213", "jane@gmail.com"])
# csv_writer.writerow(["John", "123213", "jane@gmail.com"])
from csv import DictWriter
with open("text.csv", "w") as file:
headers = ["Name", "Phone", "Email"]
csv_writer = DictWriter(file, fieldnames=headers)
csv_writer.writeheader()
csv_writer.writerow(
{"Name": "John Doe", "Phone": "1123214", "Email": "john@gmail.com"}
)
csv_writer.writerow(
{"Name": "Jane Doe", "Phone": "1123214", "Email": "john@gmail.com"}
)
# import pickle
# class User:
# def __init__(self, name, email):
# self.name = name
# self.email = email
# def __repr__(self):
# return self.name
# def greet(self):
# return f"Hello, I am {self.name}. You can reach me at {self.email}."
# john = User("John Doe", "john@gmail.com")
# jane = User("Jane Doe", "jane@yahoo.com")
# print(john.greet())
# print(jane.greet())
# with open("users.pickle", "wb") as file:
# pickle.dump((john, jane), file)
# with open("users.pickle", "rb") as file:
# john, jane = pickle.load(file)
# print(john.greet())
# print(jane.greet())
# import json
# import jsonpickle
# john = User("John Doe", "john@gmail.com")
# jane = User("Jane Doe", "jane@yahoo.com")
# print(json.dumps(john))
# print([john.__dict__, jane.__dict__])
# with open("users.json", "w") as file:
# stored = jsonpickle.encode(john)
# file.write(stored)
# with open("users.json") as file:
# restored_user = jsonpickle.decode(file.read())
# print(type(restored_user))
# john.doe@yahoo-mail.com
# import re
# # pattern = re.compile(r"\d{3}\s\d{4}-\d{4}")
# # res = pattern.search("Call us today on 022 1234-5678")
# # print(res)
# # print(res.group())
# # res2 = pattern.findall("Call use today on 022 1234-5678 or 021 0987-6543.")
# # print(res2)
# def extract_phone(input):
# phone_regex = re.compile(r"\d{3}\s\d{4}-\d{4}")
# match = phone_regex.search(input)
# if match:
# return match.group()
# return None
# # print(extract_phone("Call use today on 022 1234-5678 or 021 0987-6543."))
# def extract_phones(input):
# phone_regex = re.compile(r"\d{3}\s\d{4}-\d{4}")
# return phone_regex.findall(input)
# # print(extract_phones("Call use today on 022 1234-5678 or 021 0987-6543."))
# def validate_phone(input):
# phone_regex = re.compile(r"^\d{3}\s?\d{4}-\d{4}$")
# match = phone_regex.search(input)
# if match:
# return True
# return False
# # print(validate_phone("0221234-5678"))
# # 0.0.0.0 - 255.255.255.255
# # 192.129.3.50
# # 900.12.23.98888
# # phone_regex = re.compile(r"\d{3}\s?\d{4}-\d{4}")
# # print(phone_regex.fullmatch(" 0221234-5678").group())
# BEAUTIFUL SOUP
html_data = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>My HTML Document</title>
</head>
<body>
<div id="first">
<h3>Hello World</h3>
<p class="blue-text imp">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam,
architecto! Harum, accusantium!
</p>
<p>Another para inside the div</p>
<section>
<p>I am the grandchild of the div</p>
<p>I am the grandchild of the div</p>
<p>I am the grandchild of the div</p>
<p>I am the grandchild of the div</p>
</section>
</div>
<p>Some paragraph outside the div</p>
<p>Some paragraph outside the div</p>
<p>Some paragraph outside the div</p>
<ul>
<li class="imp">
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis,
cupiditate.
</li>
<li class="bangladesh">Lorem ipsum dolor sit amet.</li>
<li><img src="https://sample.com/img.png" alt="Paneer Soup" /></li>
</ul>
<ol>
<li class="bangladesh">
I am from the OL. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis,
cupiditate.
</li>
<li>Lorem ipsum dolor sit amet.</li>
</ol>
<h3>Hello Universe</h3>
</body>
</html>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_data, "html.parser")
# print(type(soup))
# print(soup.body.div.h3)
# print(type(soup.find("h3")))
# print(soup.find_all("h3"))
# print(soup.find_all("li"))
# print(soup.find(id="first"))
# print(soup.find_all(class_="imp"))
# print(soup.select("#first"))
# print(soup.select(".imp"))
# print(soup.select("[src]"))
# print(soup.select("[class]"))
# print(soup.select("[class='imp']"))
# print(soup.select("ul .bangladesh"))
# print(soup.select("div > p"))
# print(soup.select("h3")[0].get_text())
# print(soup.find("p").get_text().strip())
# p = soup.find("p").get_text().strip()
# print(" ".join(p.split(" ")))
# Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam, architecto! Harum, accusantium!
# print(soup.find("img").attrs)
# print(soup.find("img").attrs["src"])
print(soup.find("img")["alt"])
# html_data = """
# <!DOCTYPE html>
# <html lang="en">
# <head>
# <meta charset="UTF-8" />
# <title>My HTML Document</title>
# </head>
# <body>
# <div id="first">
# <h3>Hello World</h3>
# <p class="blue-text imp">
# Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam,
# architecto! Harum, accusantium!
# </p>
# <p>Another para inside the div</p>
# <section>
# <p>I am the grandchild of the div</p>
# <p>I am the grandchild of the div</p>
# <p>I am the grandchild of the div</p>
# <p>I am the grandchild of the div</p>
# </section>
# </div>
# <p>Some paragraph outside the div</p>
# <p>Some paragraph outside the div</p>
# <p>Some paragraph outside the div</p>
# <ul>
# <li class="imp">
# Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis,
# cupiditate.
# </li>
# <li class="bangladesh">Lorem ipsum dolor sit amet.</li>
# <li><img src="https://sample.com/img.png" alt="Paneer Soup" /></li>
# </ul>
# <ol>
# <li class="bangladesh">
# I am from the OL. Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis,
# cupiditate.
# </li>
# <li>Lorem ipsum dolor sit amet.</li>
# </ol>
# <h3>Hello Universe</h3>
# </body>
# </html>
# """
# from bs4 import BeautifulSoup
# soup = BeautifulSoup(html_data, "html.parser")
# # ulst = soup.find("ul")
# # print(ulst.contents[3])
# para = soup.find(class_="imp")
# # print(para)
# # print(para.find_next_sibling().find_next_sibling())
# # print(para.find_previous_sibling())
# print(para.find_parent().find_parent().find_parent())
import requests
from bs4 import BeautifulSoup
from csv import DictWriter, writer
from time import sleep
from random import choice
# response = requests.get("https://www.vox.com/")
# # response = requests.get("https://www.arstechnica.com/")
# soup = BeautifulSoup(response.text, "html.parser")
# articles = soup.find_all(class_="c-entry-box--compact")
# # data = []
# data.append({"title": title, "link": link, "author": author})
# with open("articles.csv", "w") as file:
# csv_writer = writer(file)
# csv_writer.writerow(["Title", "Link", "Author"])
# for article in articles:
# title = article.find("h2").find("a").get_text()
# link = article.find("h2").find("a")["href"]
# author = (
# article.find(class_="c-byline__author-name").get_text()
# if article.find(class_="c-byline__author-name")
# else ""
# )
# csv_writer.writerow([title, link, author])
# BASE_URL = "https://www.arstechnica.com"
# data = []
# url = "/page/1"
# while url:
# response = requests.get(f"{BASE_URL}{url}")
# soup = BeautifulSoup(response.text, "html.parser")
# articles = soup.find_all(class_="article")
# for article in articles:
# title = article.find("h2").find("a").get_text()
# excerpt = article.find(class_="excerpt").get_text()
# link = article.find("a")["href"]
# thumbnail = article.find("figure").find("div")["style"][22:-3]
# author = article.find("span").get_text()
# published_on = article.find("time").get_text()
# data.append(
# {
# "title": title,
# "excerpt": excerpt,
# "link": link,
# "thumbnail": thumbnail,
# "author": author,
# "published_on": published_on,
# }
# )
# with open("articles.csv", "w") as file:
# headers = ["title", "excerpt", "link", "thumbnail", "author", "published_on"]
# csv_writer = DictWriter(
# file,
# fieldnames=headers,
# )
# csv_writer.writeheader()
# for article in data:
# csv_writer.writerow(article)
BASE_URL = "https://www.arstechnica.com"
data = []
url = "/page/1"
while url:
print(f"Now scraping {BASE_URL}{url}")
response = requests.get(f"{BASE_URL}{url}")
soup = BeautifulSoup(response.text, "html.parser")
articles = soup.find_all(class_="article")
for article in articles:
title = article.find("h2").find("a").get_text()
excerpt = article.find(class_="excerpt").get_text()
link = article.find("a")["href"]
thumbnail = article.find("figure").find("div")["style"][22:-3]
author = article.find("span").get_text()
published_on = article.find("time").get_text()
with open("articles.csv", "a") as file:
csv_writer = writer(file)
csv_writer.writerow([title, excerpt, link, thumbnail, author, published_on])
next_btn = soup.find(class_="prev-next-links").find("a")["href"]
sleep(choice([1, 2, 0.3, 0.7, 1.2]))
if next_btn:
url = next_btn
else:
break
# https://books.toscrape.com/
# https://quotes.toscrape.com/
# from selenium import webdriver
# from selenium.webdriver.common.keys import Keys
# from selenium.webdriver.chrome.service import Service
# from time import sleep
# service = Service(
# "/home/rahul/Desktop/Class/Python/oct_26_2021_daily/scratchpads/chromedriver"
# )
# options = webdriver.ChromeOptions()
# browser = webdriver.Chrome(service=service, options=options)
# browser.maximize_window()
# # browser.get("https://www.youtube.com")
# # sleep(7)
# # search_box = browser.find_element_by_xpath(
# # "/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div[1]/div[1]/input"
# # )
# # search_box.click()
# # search_box.send_keys("spiderman trailer", Keys.ENTER)
# # sleep(7)
# # browser.find_element_by_partial_link_text("SPIDER-MAN: NO WAY HOME").click()
# # sleep(10)
# # try:
# # browser.find_element_by_class_name("ytp-ad-skip-button").click()
# # except:
# # print("No Ads Found")
# # sleep(15)
# # browser.get("https://www.google.com")
# # --------------
# browser.get("https://web.whatsapp.com")
# sleep(12)
# search_input = browser.find_element_by_xpath(
# "/html/body/div[1]/div[1]/div[1]/div[3]/div/div[1]/div/label/div/div[2]"
# )
# search_input.click()
# search_input.send_keys("PYTHON Even RS 22/10", Keys.ENTER)
# i = 0
# while i < 20:
# msg_input = browser.find_element_by_xpath(
# "/html/body/div[1]/div[1]/div[1]/div[4]/div[1]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[2]"
# )
# msg_input.click()
# msg_input.send_keys("Hello from Python", Keys.ENTER)
# i += 1
# sleep(5)
# browser.quit()
# import sqlite3
# data = ("John", "Doe", 25)
# data_list = [
# ("Jack", "Doe", 30),
# ("James", "Smith", 43),
# ("Peter", "Parker", 28),
# ("Mary", "Jane", 24),
# ]
# conn = sqlite3.connect("pystudents.db")
# c = conn.cursor()
# # c.execute("CREATE TABLE students (first_name TEXT, last_name TEXT, age INTEGER);")
# # c.execute(
# # 'INSERT INTO students (first_name, last_name, age) VALUES ("Harry", "Osbourne", 29);'
# # )
# query = """INSERT INTO students VALUES (?, ?, ?)"""
# # c.execute(query, data)
# # c.executemany(query, data_list)
# for item in data_list:
# print(f"Writing {item[0]} {item[1]} to database...")
# c.execute(query, item)
# conn.commit()
# conn.close()
# import collections
# from pymongo import MongoClient
# client = MongoClient("mongodb://127.0.0.1:27017")
# db = client.pystudents
# coll = db["students"]
# doc = {"firstName": "John", "lastName": "Doe", "age": 25}
# users = [
# {"firstName": "Peter", "lastName": "Parker", "age": 28},
# {"firstName": "Harry", "lastName": "Osbourne", "age": 32},
# {"firstName": "Mary Jane", "lastName": "Watson", "age": 25},
# {"firstName": "Matt", "lastName": "Murdock", "age": 34},
# ]
# # coll.insert_one(doc)
# # coll.insert_many(users)
# search_res = coll.find({"firstName": "Harry"})
# # for item in search_res:
# # print(item)
# print(list(search_res))
# client.drop_database("pystudents")
# Bank Account Management
# Bank class
# Instance attributes
# name (str)
# initial (str)
# address (str)
# phone (str[])
# ifsc_code (str) -> validation
# micr_code (int) -> validation
# _customer_list (Customer[])
# _total_customer_count (int)
# _total_balance (float)
# -> init -> sqlite3.connect(f"{name}.db")
# Instance methods
# get_bank_details()
# -----PROPERTIES----- @property
# name, initial, address, phone, ifsc_code, micr_code
# --------------------
# get_customer_count()
# get_customer_list()
# find_customer_by_name(str) -> reading sql/mongodb
# find_customer_by_email(str)
# create_customer(first_name, ....)
# ------CUSTOMERS COLLETION
# ______# new_cus = Cutomer()
# ------new_cus -> add mongodb/sql
# delete_customer(ac_no)
# export_customer_list() -> create a csv file
# Customer class
# Instance attributes
# first_name
# last_name
# phone -> validation (regex)
# address
# email -> validation (regex)
# aadhaar_card_no (int) -> validation
# pan_card_no -> validation
# balance (float) (default = 0)
# _account_no (auto_generate)
# _bank_info (bank name)
# Instance methods
# deposit()
# withdraw()
# update_name(first_name, last_name)
# update_phone()
# update_address()
# ...rest
# get_details()
# get_balance()
# ---------------
# sbi = Bank("", "", "", ifsc_code="HJ86HA12S")
# john = sbi.create_customer(...)
# import random
# chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
# # 10 chars long
# ac_no = ""
# for _ in range(10):
# ac_no += random.choice(chars)
# utils.py
# import docx
# from docx.enum.text import WD_ALIGN_PARAGRAPH
# from docx.shared import Inches
# doc = docx.Document()
# doc.add_heading("Programatic Microsoft Document Creation", level=0)
# doc.add_heading("This is a subtitle", level=2)
# para = doc.add_paragraph(
# "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur distinctio, cum quis unde assumenda animi? Mollitia similique, cumque saepe, maxime eum iusto facilis voluptate minus fugiat ratione quia obcaecati tempore."
# )
# appended_text = para.add_run(
# "\n\nProvident temporibus delectus ipsum, veritatis fuga labore?"
# )
# appended_text.bold = True
# doc.add_heading("New Heading", level=4)
# para2 = doc.add_paragraph(
# "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Dolorem magni, vitae exercitationem unde in totam harum molestiae debitis? Quasi enim, vel perferendis perspiciatis, nam expedita officiis quae excepturi nulla alias fugit molestiae cumque? Provident temporibus delectus ipsum, veritatis fuga labore?"
# )
# para2.alignment = WD_ALIGN_PARAGRAPH.RIGHT
# doc.add_page_break()
# doc.add_heading("Second page", level=1)
# doc.add_picture("py.png", width=Inches(4.0))
# doc.save("test.docx")
# import openpyxl
# wb = openpyxl.Workbook()
# sheet = wb.active
# sheet.title = "My Excel Sheet"
# 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("users.xlsx")
# path = "users.xlsx"
# wb = openpyxl.load_workbook(path)
# sheet = wb.active
# data = [
# ["John", "Doe", "123456789", "john@gmail.com"],
# ["Jane", "Doe", "123456789", "jane@gmail.com"],
# ["Jack", "Doe", "123456789", "jack@gmail.com"],
# ]
# i = 2
# while i < (len(data) + 2):
# j = 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!")
# import tkinter as tk
# root = tk.Tk()
# label = tk.Label(root, text="Hello World")
# label.pack()
# root.mainloop()
import tkinter as tk
root = tk.Tk()
root.title("Coffee Survey")
root.geometry("640x480+300+300")
root.resizable(False, False)
title = tk.Label(
root, text="Please take the survey", font=("Arial 16 bold"), bg="brown", fg="#fff"
)
# title.pack()
name_var = tk.StringVar(root)
name_label = tk.Label(root, text="What is your name?")
name_inp = tk.Entry(root, textvariable=name_var)
print(name_var.get())
drinker_var = tk.BooleanVar()
drinker_inp = tk.Checkbutton(
root, variable=drinker_var, text="Check this box if you drink coffee"
)
num_var = tk.IntVar(value=3)
num_label = tk.Label(root, text="How many cups of coffee do you drink per day?")
num_inp = tk.Spinbox(root, textvariable=num_var, from_=0, to=20, increment=1)
strength_var = tk.StringVar(value="Any")
strength_label = tk.Label(root, text="How strong do you like your coffee?")
# strength_inp = tk.Listbox(root, height=1)
strength_choices = ("Any", "Light", "Medium", "Strong", "Insane")
strength_inp = tk.OptionMenu(root, strength_var, *strength_choices)
# for choice in strength_choices:
# strength_inp.insert(tk.END, choice)
country_var = tk.BooleanVar()
country_label = tk.Label(root, text="Do you drink Indonesian coffee?")
country_frame = tk.Frame(root)
country_yes_inp = tk.Radiobutton(
country_frame, text="Yes", value=False, variable=country_var
)
country_no_inp = tk.Radiobutton(
country_frame, text="Nah! I prefer Arabian", value=False, variable=country_var
)
comment_label = tk.Label(root, text="Please write your comments")
comment_inp = tk.Text(root, height=3)
submit_btn = tk.Button(root, text="Submit Survey")
output_var = tk.StringVar(value="")
output_line = tk.Label(root, textvariable=output_var, justify="left", anchor="w")
title.grid(columnspan=2)
name_label.grid(row=1, column=0)
name_inp.grid(row=1, column=1)
drinker_inp.grid(row=2, column=0)
num_label.grid(row=3, stick=tk.W)
num_inp.grid(row=3, column=1, sticky=(tk.W + tk.E))
strength_label.grid(row=4, column=0)
strength_inp.grid(row=4, column=1)
country_yes_inp.pack(side="left", fill="x", ipadx=10, ipady=5)
country_no_inp.pack(side="left", fill="x", ipadx=10, ipady=5)
country_label.grid(row=5, columnspan=2, stick=tk.W)
country_frame.grid(row=6, columnspan=2, stick=tk.W)
comment_label.grid(row=7, sticky=tk.W)
comment_inp.grid(row=8, columnspan=2, stick="NSEW")
submit_btn.grid(row=99)
output_line.grid(row=100, columnspan=2, sticky="NSEW")
root.columnconfigure(1, weight=1)
root.rowconfigure(99, weight=2)
root.rowconfigure(100, weight=1)
def on_submit():
name = name_var.get()
number = num_var.get()
strength = strength_var.get()
country = country_var.get()
comment = comment_inp.get("1.0", tk.END)
message = f"Thanks for taking the survey, {name}.\n"
message += f"{number} - {strength} - {country}\n {comment}"
output_var.set(message)
submit_btn.configure(command=on_submit)
root.mainloop()