Contact Storing

names = []

phone_numbers = []

num = 3

for i in range(num):

    name = input("Name: ")

    phone_number = input("Phone Number: ")

    names.append(name)

    phone_numbers.append(phone_number)

print("\nName\t\t\tPhone Number\n")

for i in range(num):

    print("{}\t\t\t{}".format(names[i], phone_numbers[i]))

search_term = input("\nEnter search term: ")

print("Search result:")

if search_term in names:

    index = names.index(search_term)

    phone_number = phone_numbers[index]

    print("Name: {}, Phone Number: {}".format(search_term, phone_number))

else:

    print("Name Not Found")

Tic Tac Toe Board

import turtle 

ws=turtle.Screen()

t=turtle.Turtle()

t.color("Blue")

t.width("2")

t.speed(2)

for i in range(4):

t.forward(300)

t.left(90)

t.penup()

t.goto(0,100)

t.pendown()

t.forward(300)

t.penup()

t.goto(0,200)

t.pendown()

t.forward(300)

t.penup()

t.goto(100,0)

t.pendown()

t.left(90)

t.forward(300)

t.penup()

t.goto(200,0)

t.pendown()

t.forward(300)

Sorting Hotel info Using Given Data

class Hotel :

sortParam='name'

def __init__(self) -> None:

self.name=''

self.roomAvl=0

self.location=''

self.rating=int

self.pricePr=0

def __lt__(self,other):

getattr(self,Hotel.sortParam)<getattr(other,Hotel.sortParam)

@classmethod

def sortByName(cls):

cls.sortParam='name'

@classmethod

def sortByRate(cls):

cls.sortParam='rating'

@classmethod

def sortByRoomAvailable(cls) :

cls.sortParam='roomAvl'

def __repr__(self) -> str:

return "PRHOTELS DATA:\nHotelName:{}\tRoom Available:{}\tLocation:{}\tRating:{}\tPricePer Room:{}".format(self.name,self.roomAvl,self.location,self.rating,self.pricePr)

class User:

def __init__(self) -> None:

self.uname=''

self.uId=0

self.cost=0

def __repr__(self) -> str:

return "UserName:{}\tUserId:{}\tBooking Cost:{}".format(self.uname,self.uId,self.cost)

def PrintHotelData(hotels):

for h in hotels:

print(h)

def SortHotelByName(hotels):

print("SORT BY NAME:")

Hotel.sortByName()

hotels.sort()

PrintHotelData(hotels)

print()

def SortHotelByRating(hotels):

print("SORT BY A RATING:")

Hotel.sortByRate()

hotels.sort()

PrintHotelData(hotels)

print()

def PrintHotelBycity(s,hotels):

print("HOTELS FOR {} LOCATION ARE:".format(s))

hotelsByLoc=[h for h in hotels if h.location==s]

PrintHotelData(hotelsByLoc)

print()

def SortByRoomAvailable(hotels):

print("SORT BY ROOM AVAILABLE:")

Hotel.sortByRoomAvailable()

hotels.sort()

PrintHotelData(hotels)

print()

def PrintUserData(userName, userId, bookingCost, hotels):

users=[]

for i in range(3) :

u=User()

u.uname = userName[i]

u.uId = userId[i]

u.cost = bookingCost[i]

users.append(u)

for i in range(len(users)) :

print(users[i],"\tHotel name:",hotels[i].name)

def HotelManagement(userName,

userId,

hotelName,

bookingCost,

rooms,

locations,

ratings,

prices):

hotels=[]

for i in range(3) :

h=Hotel()

h.name = hotelName[i]

h.roomAvl = rooms[i]

h.location = locations[i]

h.rating = ratings[i]

h.pricePr = prices[i]

hotels.append(h)

print()

PrintHotelData(hotels)

SortHotelByName(hotels)

SortHotelByRating(hotels)

PrintHotelBycity("Bangalore",

hotels)

SortByRoomAvailable(hotels)

PrintUserData(userName,

userId,

bookingCost,

hotels)

if __name__ == '__main__':

userName = ["U1", "U2", "U3"]

userId = [2, 3, 4] 

hotelName = ["H1", "H2", "H3"] 

bookingCost = [1000, 1200, 1100]

rooms = [4, 5, 6] 

locations = ["Bangalore",

"Bangalore",

"Mumbai"]

ratings = [5, 5, 3]

prices = [100, 200, 100] 

HotelManagement(userName, userId,

hotelName, bookingCost,

rooms, locations,

ratings, prices)


Sales Management App

import tkinter as tk

from tkinter import messagebox

import sqlite3

root_window = tk.Tk()

root_window.title("Sales Management App")

root_window.geometry("720x750")

name_entry_text = tk.StringVar()

id_entry_text = tk.StringVar()

quantity_sold_entry_text = tk.StringVar()

quantity_left_entry_text = tk.StringVar()

price_entry_text = tk.StringVar()

today_sales_quantity_entry_text = tk.StringVar()

today_sales_total_price_entry_text = tk.StringVar()

week_sales_quantity_entry_text = tk.StringVar()

week_sales_total_price_entry_text = tk.StringVar()

month_sales_quantity_entry_text = tk.StringVar()

month_sales_total_price_entry_text = tk.StringVar()

delete_entry = tk.StringVar()

name_entry = tk.Entry(root_window, textvariable=name_entry_text)

id_entry = tk.Entry(root_window, textvariable=id_entry_text)

quantity_sold_entry = tk.Entry(root_window, textvariable=quantity_sold_entry_text)

quantity_left_entry = tk.Entry(root_window, textvariable=quantity_left_entry_text)

price_entry = tk.Entry(root_window, textvariable=price_entry_text)

today_sales_quantity_entry = tk.Entry(root_window, textvariable=today_sales_quantity_entry_text)

today_sales_total_price_entry = tk.Entry(root_window, textvariable=today_sales_total_price_entry_text)

week_sales_quantity_entry = tk.Entry(root_window, textvariable=week_sales_quantity_entry_text)

week_sales_total_price_entry = tk.Entry(root_window, textvariable=week_sales_total_price_entry_text)

month_sales_quantity_entry = tk.Entry(root_window, textvariable=month_sales_quantity_entry_text)

month_sales_total_price_entry = tk.Entry(root_window, textvariable=month_sales_total_price_entry_text)

delete_entry = tk.Entry(root_window, textvariable=delete_entry, width=20)

delete_entry.grid(row=6, column=3, padx=10, columnspan=3, rowspan=2)

delete_entry.insert(0, 'Enter id to delete')

name_label = tk.Label(root_window, text="Product name")

id_label = tk.Label(root_window, text="Product ID")

quantity_sold_label = tk.Label(root_window, text="Quantity sold")

quantity_left_label = tk.Label(root_window, text="Quantity left")

price_label = tk.Label(root_window, text="Price")

today_sales_quantity_label = tk.Label(root_window, text="Today's Sales(quantity)")

today_sales_total_price_label = tk.Label(root_window, text="Today's Sales(Total Price)")

week_sales_quantity_label = tk.Label(root_window, text="Week Sales(quantity)")

week_sales_total_price_label = tk.Label(root_window, text="Week Sales(Total Price)")

month_sales_quantity_label = tk.Label(root_window, text="Month Sales(quantity)")

month_sales_total_price_label = tk.Label(root_window, text="Month Sales(Total Price)")

product_list_label = tk.Label(root_window, text='Product List', font=(30), borderwidth=1, relief="solid", width=50)

product_list_label.grid(row=12, column=0, columnspan=50, pady=20)

pdt_name = tk.Label(root_window, text='Product Name', borderwidth=1, relief="solid")

pdt_id = tk.Label(root_window, text='Product ID', borderwidth=1, relief="solid")

pdt_price = tk.Label(root_window, text='Product Price', borderwidth=1, relief="solid")

pdt_sales_quantity = tk.Label(root_window, text="Today's Sales(Quantity)", borderwidth=1, relief="solid")

def Refresh():

    conn = sqlite3.connect('database.db')

    cursor = conn.cursor()

    cursor.execute("CREATE TABLE IF NOT EXISTS products (name TEXT, id TEXT PRIMARY KEY, quantitySold TEXT, quantityLeft TEXT, price TEXT, todaySalesQuantity TEXT, todaySalesTotalPrice TEXT, weekSalesQuantity TEXT, weekSalesTotalPrice TEXT, monthSalesQuantity TEXT, monthSalesTotalPrice TEXT)")

    cursor.execute('SELECT * FROM products')

    products = cursor.fetchall()

    for i in range(len(products)):

        tk.Label(root_window, text=products[i][0]).grid(row=i+14, column=0)

        tk.Label(root_window, text=products[i][1]).grid(row=i+14, column=1)

        tk.Label(root_window, text=products[i][4]).grid(row=i+14, column=2)

        tk.Label(root_window, text=products[i][5]).grid(row=i+14, column=3)

    conn.close()

def show_message(title, message):

    messagebox.showerror(title, message)

def add_product():

    try:

        conn = sqlite3.connect("database.db")

        cursor = conn.cursor()

        cursor.execute("INSERT INTO products (name, id, quantitySold, quantityLeft, price, todaySalesQuantity, todaySalesTotalPrice, weekSalesQuantity, weekSalesTotalPrice, monthSalesQuantity, monthSalesTotalPrice) VALUES (?, ?, ?, ?,?,?,?,?,?,?,?)", (str(name_entry_text.get()), str(id_entry_text.get()), str(quantity_sold_entry_text.get()), str(quantity_left_entry_text.get()), str(price_entry_text.get()), str(today_sales_quantity_entry_text.get()), str(today_sales_total_price_entry_text.get()), str(week_sales_quantity_entry_text.get()), str(week_sales_total_price_entry_text.get()), str(month_sales_quantity_entry_text.get()), str(month_sales_total_price_entry_text.get())))

        conn.commit()

    except sqlite3.Error as e:

        show_message('Sqlite error', e)

    finally:

        Refresh()

        conn.close()

def delete_product():

    try:

        conn = sqlite3.connect("database.db")

        cursor = conn.cursor()

        cursor.execute('SELECT * FROM products')

        cursor.execute("DELETE FROM products WHERE id = ?", (str(delete_entry.get())))

        conn.commit()

        show_message('Success', 'Product deleted')

        conn.close()

        Refresh()

    except sqlite3.Error as e:

        show_message('Sqlite error', e)

    finally:

        conn.close()

        Refresh()

def update():

    price = price_entry_text.get()

    quantity_sold = quantity_sold_entry_text.get()

    quantity_left = quantity_left_entry_text.get()

    today_sales_quantity = today_sales_quantity_entry_text.get()

    week_sales_quantity = week_sales_quantity_entry_text.get()

    month_sales_quantity = month_sales_quantity_entry_text.get()

    if len(price) < 1 or len(quantity_sold) < 1 or len(quantity_left) < 1 or len(today_sales_quantity) < 1 or len(week_sales_quantity) < 1 or len(month_sales_quantity) < 1:

        show_message('Python error!', 'Please enter values for all fields')

        return

    try:

        price = int(price)

        quantity_sold = int(quantity_sold)

        quantity_left = int(quantity_left)

        today_sales_quantity = int(today_sales_quantity)

        week_sales_quantity = int(week_sales_quantity)

        month_sales_quantity = int(month_sales_quantity)

        conn = sqlite3.connect('database.db')

        c = conn.cursor()

        c.execute("UPDATE products SET name=?, id=?, quantitySold=?, quantityLeft=?, price=?, todaySalesQuantity=?, todaySalesTotalPrice=?, weekSalesQuantity=?, weekSalesTotalPrice=?, monthSalesQuantity=?, monthSalesTotalPrice=?  WHERE id=?", (str(name_entry_text.get()), str(id_entry_text.get()), str(quantity_sold_entry_text.get()), str(quantity_left_entry_text.get()), str(price_entry_text.get()), str(today_sales_quantity_entry_text.get()), str(today_sales_total_price_entry_text.get()), str(week_sales_quantity_entry_text.get()), str(week_sales_total_price_entry_text.get()), str(month_sales_quantity_entry_text.get()), str(month_sales_total_price_entry_text.get()), str(id_entry_text.get())))

        conn.commit()

        Refresh()

        show_message('Success', 'Product updated')

        conn.close()

    except sqlite3.Error as e:

        show_message('Sqlite error', e)

    finally:

        Refresh()

        conn.close()

def calculate():

    price = price_entry_text.get()

    quantity_sold = quantity_sold_entry_text.get()

    quantity_left = quantity_left_entry_text.get()

    today_sales_quantity = today_sales_quantity_entry_text.get()

    week_sales_quantity = week_sales_quantity_entry_text.get()

    month_sales_quantity = month_sales_quantity_entry_text.get()

    if len(price) < 1 or len(quantity_sold) < 1 or len(quantity_left) < 1 or len(today_sales_quantity) < 1 or len(week_sales_quantity) < 1 or len(month_sales_quantity) < 1:

        show_message('Python error!', 'Please enter values for all fields')

        return

    try:

        price = int(price)

        quantity_sold = int(quantity_sold)

        quantity_left = int(quantity_left)

        today_sales_quantity = int(today_sales_quantity)

        week_sales_quantity = int(week_sales_quantity)

        month_sales_quantity = int(month_sales_quantity)

    except:

        show_message('Python error!', 'Please enter integer values in these fields-> Price, Today Sales(Quantity), Week Sales(Quantity), Month Sales(Quantity)')

        return

    today_sales_total_price = price * today_sales_quantity

    week_sales_total_price = price * week_sales_quantity

    month_sales_total_price = price * month_sales_quantity


    today_sales_total_price_entry_text.set(today_sales_total_price)

    week_sales_total_price_entry_text.set(week_sales_total_price)

    month_sales_total_price_entry_text.set(month_sales_total_price)

    add_button.config(state='normal')

Refresh()

update_button = tk.Button(text='UPDATE', width=20, height=2, command=update)

delete_button = tk.Button(text='DELETE', width=20,height=2, command=delete_product)

add_button = tk.Button(text='ADD', width=20, height=2, command=add_product)

add_button.config(state='disabled')

calculate_button = tk.Button(text='Verify And Calculate Prices', width=25, height=2, command=calculate)

refresh_button = tk.Button(text='Refresh Table', width=25, height=2, command=Refresh)

name_label.grid(row=0, column=0, padx=10, pady=10, sticky='w')

id_label.grid(row=1, column=0, padx=10, pady=10, sticky='w')

quantity_sold_label.grid(row=2, column=0, padx=10, pady=10, sticky='w')

quantity_left_label.grid(row=3, column=0, padx=10, pady=10, sticky='w')

price_label.grid(row=4, column=0, padx=10, pady=10, sticky='w')

today_sales_quantity_label.grid(row=5, column=0, padx=10, pady=10, sticky='w')

today_sales_total_price_label.grid(row=6, column=0, padx=10, pady=10, sticky='w')

week_sales_quantity_label.grid(row=7, column=0, padx=10, pady=10, sticky='w')

week_sales_total_price_label.grid(row=8, column=0, padx=10, pady=10, sticky='w')

month_sales_quantity_label.grid(row=9, column=0, padx=10, pady=10, sticky='w')

month_sales_total_price_label.grid(row=10, column=0, padx=10, pady=10, sticky='w')

name_entry.grid(row=0, column=1, padx=10, pady=10, sticky='w')

id_entry.grid(row=1, column=1, padx=10, pady=10, sticky='w')

quantity_sold_entry.grid(row=2, column=1, padx=10, pady=10, sticky='w')

quantity_left_entry.grid(row=3, column=1, padx=10, pady=10, sticky='w')

price_entry.grid(row=4, column=1, padx=10, pady=10, sticky='w')

today_sales_quantity_entry.grid(row=5, column=1, padx=10, pady=10, sticky='w')

today_sales_total_price_entry.grid(row=6, column=1, padx=10, pady=10, sticky='w')

today_sales_total_price_entry.config(state='disabled')

week_sales_quantity_entry.grid(row=7, column=1, padx=10, pady=10, sticky='w')

week_sales_total_price_entry.grid(row=8, column=1, padx=10, pady=10, sticky='w')

week_sales_total_price_entry.config(state='disabled')

month_sales_quantity_entry.grid(row=9, column=1, padx=10, pady=10, sticky='w')

month_sales_total_price_entry.grid(row=10, column=1, padx=10, pady=10, sticky='w')

month_sales_total_price_entry.config(state='disabled')

update_button.grid(row=3, column=2, rowspan=2, padx=15)

delete_button.grid(row=6, column=2, rowspan=2, padx=15)

calculate_button.grid(row=11, column=0, columnspan=2)

add_button.grid(row=11, column=2)

refresh_button.grid(row=11, column=3)

pdt_name.grid(row=13, column=0)

pdt_id.grid(row=13, column=1)

pdt_price.grid(row=13, column=2)

pdt_sales_quantity.grid(row=13, column=3)

root_window.mainloop()

App For Download File from URL

from tkinter import *

from tkinter import messagebox

from PIL import ImageTk, Image

import tkinter.font as font

import requests

import re

import validators

import os

from urllib.parse import urlparse

root = Tk()

root.title("Download File from URL")

icon = PhotoImage(file='image.png')

root.iconphoto(False, icon)

root.minsize(600, 500)

root.maxsize(600, 500)

HEIGHT = 500

WIDTH = 500

FONT = font.Font(family="Comic Sans MS", size="10", weight="bold")

canvas = Canvas(root, height=HEIGHT, width=WIDTH)

canvas.pack()

background_image = ImageTk.PhotoImage(

    Image.open(r"image.jpg"))

background_label = Label(root, image=background_image)

background_label.place(relwidth=1, relheight=1)

frame = Frame(root, bg="yellow", bd=5)

frame.place(relx=0.5, rely=0.1, relwidth=0.80, relheight=0.25, anchor="n")

label_up = Label(frame)

label_up.place(relwidth=1, relheight=1)

label1 = Label(frame, text="Enter the URL", font=FONT, bd=5,

               bg="#fc034e", highlightbackground="#d9138a", fg="black")

label1.place(relx=0.1, rely=0.1, relwidth=0.25, relheight=0.25)

label2 = Label(frame, text="Enter Filename", font=FONT, bd=5,

               bg="#fc034e", highlightbackground="#d9138a", fg="black")

label2.place(relx=0.1, rely=0.64, relwidth=0.25, relheight=0.25)

entry1 = Entry(frame, font=FONT, fg="#001a4d")

entry1.place(relx=0.54, rely=0.1, relwidth=0.4, relheight=0.25)

entry2 = Entry(frame, font=FONT, fg="#001a4d")

entry2.place(relx=0.54, rely=0.64, relwidth=0.4, relheight=0.25)

def download(url, name):

    valid = validators.url(url)

    if (valid != True):

        messagebox.showerror("Invalid URL", "URL is invalid")

    elif (url == ""):

        messagebox.showerror("No valid URL", "URL cannot be empty")

    else:

        response = requests.get(url, allow_redirects=True)

        rhead = response.headers['Content-Type']

        if (canbedownloaded(rhead)):

            if (name == ""):

                a = urlparse(url)

                name = os.path.basename(a.path)

            file_data = rhead.split('/')

            ext = file_data[1]

            filename = name+'.'+ext

            open(filename, "wb").write(response.content)

            label_down['text'] = f"Your file {filename}\n has been downloaded successfully."

        else:

            label_down['text'] = "This file is invalid. It can not be downloaded."

def canbedownloaded(rhead):

    if 'text' in rhead.lower():

        return False

    if 'html' in rhead.lower():

        return False

    return True

def clear():

    entry1.delete(0, END)

    entry2.delete(0, END)

    label_down['text'] = ""

button1 = Button(root, text="DOWNLOAD", font=FONT, bg="pink", fg="black", activeforeground="pink",

                 activebackground="black", command=lambda: download(entry1.get(), entry2.get()))

button1.place(relx=0.25, rely=0.4, relwidth=0.19, relheight=0.07)

button2 = Button(root, text="CLEAR", font=FONT, bg="pink", fg="black",

                 activeforeground="pink", activebackground="black", command=clear)

button2.place(relx=0.55, rely=0.4, relwidth=0.19, relheight=0.07)

lower_frame = Frame(root, bg="yellow", bd=10)

lower_frame.place(relx=0.5, rely=0.53, relwidth=0.8,

                  relheight=0.25, anchor="n")

label_down = Label(lower_frame, font=FONT, fg="#001a4d",

                   anchor="nw", justify="left", bd=4)

label_down.place(relwidth=1, relheight=1)

root.mainloop()