Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Intenship

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

1.

To-Do List Application: Create a command-line or GUI-based to-do list


application that allows users to add, view, and delete tasks. You can also add
features like due dates and priority levels.
Program to -do list applications:
import json

import datetime

# File to store tasks

FILE_NAME = "tasks.json"

def load_tasks():

try:

with open(FILE_NAME, "r") as f:

return json.load(f)

except (FileNotFoundError, json.JSONDecodeError):

return []

def save_tasks(tasks):

with open(FILE_NAME, "w") as f:

json.dump(tasks, f, indent=4)

def add_task():

title = input("Enter task title: ")

due_date = input("Enter due date (YYYY-MM-DD): ")

priority = input("Enter priority (high, medium, low): ")

task = {

"title": title,

"due_date": due_date,

"priority": priority

}
tasks = load_tasks()

tasks.append(task)

save_tasks(tasks)

print("Task added successfully.")

def view_tasks():

tasks = load_tasks()

if not tasks:

print("No tasks found.")

return

for idx, task in enumerate(tasks, 1):

print(f"{idx}. {task['title']} (Due: {task['due_date']}, Priority: {task['priority']})")

def delete_task():

view_tasks()

try:

task_num = int(input("Enter task number to delete: "))

tasks = load_tasks()

if 1 <= task_num <= len(tasks):

del tasks[task_num - 1]

save_tasks(tasks)

print("Task deleted successfully.")

else:

print("Invalid task number.")

except ValueError:

print("Please enter a valid number.")

def main():
while True:

print("\nTo-Do List")

print("1. Add Task")

print("2. View Tasks")

print("3. Delete Task")

print("4. Exit")

choice = input("Choose an option: ")

if choice == "1":

add_task()

elif choice == "2":

view_tasks()

elif choice == "3":

delete_task()

elif choice == "4":

print("Exiting...")

break

else:

print("Invalid option. Please try again.")

if __name__ == "__main__":

main()

Output:
To-Do List

1. Add Task

2. View Tasks

3. Delete Task

4. Exit

Choose an option: 1

Enter task title: calculator in python program

Enter due date (YYYY-MM-DD): 2024-11-16


Enter priority (high, medium, low): high

Task added successfully.

To-Do List

1. Add Task

2. View Tasks

3. Delete Task

4. Exit

Choose an option: 1

Enter task title: table layout in mobile application development

Enter due date (YYYY-MM-DD): 2024-11-20

Enter priority (high, medium, low): high

Task added successfully.

To-Do List

1. Add Task

2. View Tasks

3. Delete Task

4. Exit

Choose an option: 1

Enter task title: web technology in student table

Enter due date (YYYY-MM-DD): 2024-11-24

Enter priority (high, medium, low): high

Task added successfully.

To-Do List

1. Add Task

2. View Tasks

3. Delete Task

4. Exit

Choose an option: 2
1. calculator in python program (Due: 2024-11-16, Priority: high)

2. table layout in mobile application development (Due: 2024-11-20, Priority: high)

3. web technology in student table (Due: 2024-11-24, Priority: high)

To-Do List

1. Add Task

2. View Tasks

3. Delete Task

4. Exit

Choose an option: 3

1. calculator in python program (Due: 2024-11-16, Priority: high)

2. table layout in mobile application development (Due: 2024-11-20, Priority: high)

3. web technology in student table (Due: 2024-11-24, Priority: high)

Enter task number to delete: 3

Task deleted successfully.

To-Do List

1. Add Task

2. View Tasks

3. Delete Task

4. Exit

Choose an option: 2

1. calculator in python program (Due: 2024-11-16, Priority: high)

2. table layout in mobile application development (Due: 2024-11-20, Priority: high)

To-Do List

1. Add Task

2. View Tasks

3. Delete Task

4. Exit

Choose an option: 4

Exiting...
2. Calculator: Build a basic calculator program that can perform arithmetic
operations (addition, subtraction, multiplication, division) based on user
input.
Program to calculator:
# pip install tkinter

import tkinter as tk

import tkinter.messagebox

from tkinter.constants import SUNKEN

window = tk.Tk()

window.title('Calculator')

frame = tk.Frame(master=window, bg="skyblue", padx=10)

frame.pack()

entry = tk.Entry(master=frame, relief=SUNKEN, borderwidth=3, width=30)

entry.grid(row=0, column=0, columnspan=3, ipady=2, pady=2)

def myclick(number):

entry.insert(tk.END, number)

def equal():

try:

y = str(eval(entry.get()))

entry.delete(0, tk.END)

entry.insert(0, y)

except:

tkinter.messagebox.showinfo("Error", "Syntax Error")


def clear():

entry.delete(0, tk.END)

button_1 = tk.Button(master=frame, text='1', padx=15,

pady=5, width=3, command=lambda: myclick(1))

button_1.grid(row=1, column=0, pady=2)

button_2 = tk.Button(master=frame, text='2', padx=15,

pady=5, width=3, command=lambda: myclick(2))

button_2.grid(row=1, column=1, pady=2)

button_3 = tk.Button(master=frame, text='3', padx=15,

pady=5, width=3, command=lambda: myclick(3))

button_3.grid(row=1, column=2, pady=2)

button_4 = tk.Button(master=frame, text='4', padx=15,

pady=5, width=3, command=lambda: myclick(4))

button_4.grid(row=2, column=0, pady=2)

button_5 = tk.Button(master=frame, text='5', padx=15,

pady=5, width=3, command=lambda: myclick(5))

button_5.grid(row=2, column=1, pady=2)

button_6 = tk.Button(master=frame, text='6', padx=15,

pady=5, width=3, command=lambda: myclick(6))

button_6.grid(row=2, column=2, pady=2)

button_7 = tk.Button(master=frame, text='7', padx=15,

pady=5, width=3, command=lambda: myclick(7))

button_7.grid(row=3, column=0, pady=2)

button_8 = tk.Button(master=frame, text='8', padx=15,

pady=5, width=3, command=lambda: myclick(8))

button_8.grid(row=3, column=1, pady=2)

button_9 = tk.Button(master=frame, text='9', padx=15,

pady=5, width=3, command=lambda: myclick(9))

button_9.grid(row=3, column=2, pady=2)


button_0 = tk.Button(master=frame, text='0', padx=15,

pady=5, width=3, command=lambda: myclick(0))

button_0.grid(row=4, column=1, pady=2)

button_add = tk.Button(master=frame, text="+", padx=15,

pady=5, width=3, command=lambda: myclick('+'))

button_add.grid(row=5, column=0, pady=2)

button_subtract = tk.Button(

master=frame, text="-", padx=15, pady=5, width=3, command=lambda: myclick('-'))

button_subtract.grid(row=5, column=1, pady=2)

button_multiply = tk.Button(

master=frame, text="*", padx=15, pady=5, width=3, command=lambda: myclick('*'))

button_multiply.grid(row=5, column=2, pady=2)

button_div = tk.Button(master=frame, text="/", padx=15,

pady=5, width=3, command=lambda: myclick('/'))

button_div.grid(row=6, column=0, pady=2)

button_clear = tk.Button(master=frame, text="clear",

padx=15, pady=5, width=12, command=clear)

button_clear.grid(row=6, column=1, columnspan=2, pady=2)

button_equal = tk.Button(master=frame, text="=", padx=15,

pady=5, width=9, command=equal)

button_equal.grid(row=7, column=0, columnspan=3, pady=2)

window.mainloop()
output:

3. Weather App: Develop a program that fetches weather data from an online
API and displays it to the user based on their location or a user-provided
location.

4.Currency Converter: Create a currency converter that can convert between


different
currencies based on real-time exchange rates obtained from an API.
Program to currency converter:
#pip install tkinter

import tkinter as tk

from tkinter import *

import tkinter.messagebox

#GUI

root = tk.Tk()

root.title("Currency converter:GeeksForGeeks")

Tops = Frame(root, bg = '#e6e5e5', pady=2, width=1850, height=100, relief="ridge")

Tops.grid(row=0, column=0)

headlabel = tk.Label(Tops, font=('lato black', 19, 'bold'), text='Currency converter :GeeksForGeeks ',

bg='#e6e5e5', fg='black')

headlabel.grid(row=1, column=0, sticky=W)

variable1 = tk.StringVar(root)

variable2 = tk.StringVar(root)

variable1.set("currency")

variable2.set("currency")

#Function To For Real Time Currency Conversion

def RealTimeCurrencyConversion():

from forex_python.converter import CurrencyRates

c = CurrencyRates()

from_currency = variable1.get()

to_currency = variable2.get()
if (Amount1_field.get() == ""):

tkinter.messagebox.showinfo("Error !!", "Amount Not Entered.\n Please a valid


amount.")

elif (from_currency == "currency" or to_currency == "currency"):

tkinter.messagebox.showinfo("Error !!",

"Currency Not Selected.\n


Please select FROM and TO Currency form menu.")

else:

new_amt = c.convert(from_currency, to_currency, float(Amount1_field.get()))

new_amount = float("{:.4f}".format(new_amt))

Amount2_field.insert(0, str(new_amount))

#clearing all the data entered by the user

def clear_all():

Amount1_field.delete(0, tk.END)

Amount2_field.delete(0, tk.END)

CurrenyCode_list = ["INR", "USD", "CAD", "CNY", "DKK", "EUR"]

root.configure(background='#e6e5e5')

root.geometry("700x400")

Label_1 = Label(root, font=('lato black', 27, 'bold'), text="", padx=2, pady=2, bg="#e6e5e5",
fg="black")

Label_1.grid(row=1, column=0, sticky=W)

label1 = tk.Label(root, font=('lato black', 15, 'bold'), text="\t Amount : ", bg="#e6e5e5", fg="black")

label1.grid(row=2, column=0, sticky=W)


label1 = tk.Label(root, font=('lato black', 15, 'bold'), text="\t From Currency : ", bg="#e6e5e5",
fg="black")

label1.grid(row=3, column=0, sticky=W)

label1 = tk.Label(root, font=('lato black', 15, 'bold'), text="\t To Currency : ", bg="#e6e5e5",
fg="black")

label1.grid(row=4, column=0, sticky=W)

label1 = tk.Label(root, font=('lato black', 15, 'bold'), text="\t Converted Amount : ", bg="#e6e5e5",
fg="black")

label1.grid(row=8, column=0, sticky=W)

Label_1 = Label(root, font=('lato black', 7, 'bold'), text="", padx=2, pady=2, bg="#e6e5e5",


fg="black")

Label_1.grid(row=5, column=0, sticky=W)

Label_1 = Label(root, font=('lato black', 7, 'bold'), text="", padx=2, pady=2, bg="#e6e5e5",


fg="black")

Label_1.grid(row=7, column=0, sticky=W)

FromCurrency_option = tk.OptionMenu(root, variable1, *CurrenyCode_list)

ToCurrency_option = tk.OptionMenu(root, variable2, *CurrenyCode_list)

FromCurrency_option.grid(row=3, column=0, ipadx=45, sticky=E)

ToCurrency_option.grid(row=4, column=0, ipadx=45, sticky=E)

Amount1_field = tk.Entry(root)

Amount1_field.grid(row=2, column=0, ipadx=28, sticky=E)

Amount2_field = tk.Entry(root)

Amount2_field.grid(row=8, column=0, ipadx=31, sticky=E)


Label_9 = Button(root, font=('arial', 15, 'bold'), text=" Convert ", padx=2, pady=2, bg="lightblue",
fg="white",

command=RealTimeCurrencyConversion)

Label_9.grid(row=6, column=0)

Label_1 = Label(root, font=('lato black', 7, 'bold'), text="", padx=2, pady=2, bg="#e6e5e5",


fg="black")

Label_1.grid(row=9, column=0, sticky=W)

Label_9 = Button(root, font=('arial', 15, 'bold'), text=" Clear All ", padx=2, pady=2, bg="lightblue",
fg="white",

command=clear_all)

Label_9.grid(row=10, column=0)

root.mainloop()

Output:

5. Random Password Generator: Build a program that generates random passwords

with user-defined length and complexity (e.g., uppercase, lowercase, numbers,

symbols).

Program to generate a random password:

import string

import random

# Getting password length

length = int(input("Enter password length: "))


print('''Choose character set for password from these :

1. Digits

2. Letters

3. Special characters

4. Exit''')

characterList = ""

# Getting character set for password

while(True):

choice = int(input("Pick a number "))

if(choice == 1):

# Adding letters to possible characters

characterList += string.ascii_letters

elif(choice == 2):

# Adding digits to possible characters

characterList += string.digits

elif(choice == 3):

# Adding special characters to possible

# characters

characterList += string.punctuation

elif(choice == 4):

break

else:

print("Please pick a valid option!")

password = []
for i in range(length):

# Picking a random character from our

# character list

randomchar = random.choice(characterList)

# appending a random character to password

password.append(randomchar)

# printing password as a string

print("The random password is " + "".join(password))

OUTPUT:

Enter password length: 10

Choose character set for password from these :

1. Digits

2. Letters

3. Special characters

4. Exit

Pick a number 1

Pick a number 2

Pick a number 3

Pick a number 4

The random password is 4?]a.e;vK/

6. Simple Blog System: Create a simple blog system where users can write,
edit, and delete blog posts. Store blog posts in text files or a lightweight
database.
Program to create a simple Blog system:
import os
import getpass
# Blog data stored in dictionaries
users = {}
posts = {}
comments = {}
def register():
username = input("Enter username: ")
password = getpass.getpass("Enter password: ")
users[username] = password
print("Registration successful!")
def login():
username = input("Enter username: ")
password = getpass.getpass("Enter password: ")
if username in users and users[username] == password:
return username
else:
print("Invalid credentials.")
return None
def create_post(username):
title = input("Enter post title: ")
content = input("Enter post content: ")
posts[title] = {"author": username, "content": content}
print("Post created!")
def view_posts():
for title, post in posts.items():
print(f"Title: {title}")
print(f"Author: {post['author']}")
print(f"Content: {post['content']}\n")
def edit_post(username):
title = input("Enter post title: ")
if title in posts and posts[title]["author"] == username:
content = input("Enter new content: ")
posts[title]["content"] = content
print("Post updated!")
else:
print("Post not found or unauthorized.")
def delete_post(username):
title = input("Enter post title: ")
if title in posts and posts[title]["author"] == username:
del posts[title]
print("Post deleted!")
else:
print("Post not found or unauthorized.")
def comment_post():
title = input("Enter post title: ")
if title in posts:
comment = input("Enter comment: ")
if title not in comments:
comments[title] = []
comments[title].append(comment)
print("Comment added!")
else:
print("Post not found.")
def view_comments():
title = input("Enter post title: ")
if title in comments:
print("Comments:")
for comment in comments[title]:
print(comment)
else:
print("No comments.")
def main():
while True:
print("1. Register")
print("2. Login")
print("3. Create Post")
print("4. View Posts")
print("5. Edit Post")
print("6. Delete Post")
print("7. Comment Post")
print("8. View Comments")
print("9. Quit")
choice = input("Choose an option: ")
if choice == "1":
register()
elif choice == "2":
username = login()
if username:
print(f"Welcome, {username}!")
elif choice == "3":
username = input("Enter username: ")
create_post(username)
elif choice == "4":
view_posts()
elif choice == "5":
username = input("Enter username: ")
edit_post(username)
elif choice == "6":
username = input("Enter username: ")
delete_post(username)
elif choice == "7":
comment_post()
elif choice == "8":
view_comments()
elif choice == "9":
break
else:
print("Invalid choice.")
if __name__ == "__main__":
main()
Output:
1. Register
2. Login
3. Create Post
4. View Posts
5. Edit Post
6. Delete Post
7. Comment Post
8. View Comments
9. Quit
Choose an option: 1
Enter username: chinni
Enter password: Chinni@4118
Registration successful!
1. Register
2. Login
3. Create Post
4. View Posts
5. Edit Post
6. Delete Post
7. Comment Post
8. View Comments
9. Quit
Choose an option: 2
Enter username: Chinni
Enter password: Chinni@4118
Invalid credentials.
1. Register
2. Login
3. Create Post
4. View Posts
5. Edit Post
6. Delete Post
7. Comment Post
8. View Comments
9. Quit
Choose an option: 3
Enter username: Chinni
Enter post title: task
Enter post content: python program
Post created!
1. Register
2. Login
3. Create Post
4. View Posts
5. Edit Post
6. Delete Post
7. Comment Post
8. View Comments
9. Quit
Choose an option: 4
Title: task
Author: Chinni
Content: python program
1. Register
2. Login
3. Create Post
4. View Posts
5. Edit Post
6. Delete Post
7. Comment Post
8. View Comments
9. Quit
Choose an option: 5
Enter username: Chinni
Enter post title: python taskl
Post not found or unauthorized.
1. Register
2. Login
3. Create Post
4. View Posts
5. Edit Post
6. Delete Post
7. Comment Post
8. View Comments
9. Quit
Choose an option: 4
Title: task
Author: Chinni
Content: python program
1. Register
2. Login
3. Create Post
4. View Posts
5. Edit Post
6. Delete Post
7. Comment Post
8. View Comments
9. Quit
Choose an option: 7
Enter post title: Python task
Post not found.
1. Register
2. Login
3. Create Post
4. View Posts
5. Edit Post
6. Delete Post
7. Comment Post
8. View Comments
9. Quit
Choose an option: 8
Enter post title: Python program
No comments.
1. Register
2. Login
3. Create Post
4. View Posts
5. Edit Post
6. Delete Post
7. Comment Post
8. View Comments
9. Quit
Choose an option: 9
7. Chat Application: Develop a basic chat application that allows users to send
and receive messages in real-time using sockets or a simple web interface .
Python program to develop Chat Application:

8.File Organizer: Build a program that organizes files in a directory by


grouping them into subdirectories based on file types (e.g., images,
documents, videos).

9. Quiz Game: Create a quiz game with multiple-choice questions. Keep track
of the player's score and provide feedback on their performance.
Program to create a quiz game:
from tkinter import *
# define question dictionary
question = {
"20+13": ['2', '33', '5', '9'],
"22-12": ['2', '10', '5'],
"10+3": ['13', '6', '9', '7'],
"15*2":['30','10','40','15'],
"100/4":['25','10','15','4']
}
# define answer list
ans = ['33', '10', '13','30','25']

current_question = 0

def start_quiz():
start_button.forget()
next_button.pack()
next_question()

def next_question():
global current_question
if current_question < len(question):
# get key or question that need to be printed
check_ans()
user_ans.set('None')
c_question = list(question.keys())[current_question]
# clear frame to update its content
clear_frame()
# printing question
Label(f1, text=f"Question : {c_question}", padx=15,
font="calibre 12 normal").pack(anchor=NW)
# printing options
for option in question[c_question]:
Radiobutton(f1, text=option, variable=user_ans,
value=option, padx=28).pack(anchor=NW)
current_question += 1
else:
next_button.forget()
check_ans()
clear_frame()
output = f"Your Score is {user_score.get()} out of {len(question)}"
Label(f1, text=output, font="calibre 25 bold").pack()
Label(f1, text="Thanks for Participating",
font="calibre 18 bold").pack()

def check_ans():
temp_ans = user_ans.get()
if temp_ans != 'None' and temp_ans == ans[current_question-1]:
user_score.set(user_score.get()+1)

def clear_frame():
for widget in f1.winfo_children():
widget.destroy()

if __name__ == "__main__":
root = Tk()
# setup basic window
root.title("GFG QUIZ APP")
root.geometry("850x520")
root.minsize(800, 400)

user_ans = StringVar()
user_ans.set('None')
user_score = IntVar()
user_score.set(0)

Label(root, text="Quiz App",


font="calibre 40 bold",
relief=SUNKEN, background="cyan",
padx=10, pady=9).pack()
Label(root, text="", font="calibre 10 bold").pack()
start_button = Button(root,
text="Start Quiz",
command=start_quiz,
font="calibre 17 bold")
start_button.pack()

f1 = Frame(root)
f1.pack(side=TOP, fill=X)

next_button = Button(root, text="Next Question",


command=next_question,
font="calibre 17 bold")

root.mainloop()
Output:
10. Alarm Clock: Design an alarm clock application that allows users to set
alarms with specific times and messages. It can play a sound or display a
message when the alarm goes off.
Program to design a Alarm Clock:
# Import Required Library
from tkinter import *
import datetime
import time
import winsound
from threading import *

# Create Object
root = Tk()

# Set geometry
root.geometry("400x200")

# Use Threading
def Threading():
t1=Thread(target=alarm)
t1.start()
def alarm():
# Infinite Loop
while True:
# Set Alarm
set_alarm_time = f"{hour.get()}:{minute.get()}:{second.get()}"

# Wait for one seconds


time.sleep(1)

# Get current time


current_time = datetime.datetime.now().strftime("%H:%M:%S")
print(current_time,set_alarm_time)

# Check whether set alarm is equal to current time or not


if current_time == set_alarm_time:
print("Time to Wake up")
# Playing sound
winsound.PlaySound("sound.wav",winsound.SND_ASYNC)

# Add Labels, Frame, Button, Optionmenus


Label(root,text="Alarm Clock",font=("Helvetica 20 bold"),fg="red").pack(pady=10)
Label(root,text="Set Time",font=("Helvetica 15 bold")).pack()

frame = Frame(root)
frame.pack()

hour = StringVar(root)
hours = ('00', '01', '02', '03', '04', '05', '06', '07',
'08', '09', '10', '11', '12', '13', '14', '15',
'16', '17', '18', '19', '20', '21', '22', '23', '24'
)
hour.set(hours[0])

hrs = OptionMenu(frame, hour, *hours)


hrs.pack(side=LEFT)

minute = StringVar(root)
minutes = ('00', '01', '02', '03', '04', '05', '06', '07',
'08', '09', '10', '11', '12', '13', '14', '15',
'16', '17', '18', '19', '20', '21', '22', '23',
'24', '25', '26', '27', '28', '29', '30', '31',
'32', '33', '34', '35', '36', '37', '38', '39',
'40', '41', '42', '43', '44', '45', '46', '47',
'48', '49', '50', '51', '52', '53', '54', '55',
'56', '57', '58', '59', '60')
minute.set(minutes[0])

mins = OptionMenu(frame, minute, *minutes)


mins.pack(side=LEFT)

second = StringVar(root)
seconds = ('00', '01', '02', '03', '04', '05', '06', '07',
'08', '09', '10', '11', '12', '13', '14', '15',
'16', '17', '18', '19', '20', '21', '22', '23',
'24', '25', '26', '27', '28', '29', '30', '31',
'32', '33', '34', '35', '36', '37', '38', '39',
'40', '41', '42', '43', '44', '45', '46', '47',
'48', '49', '50', '51', '52', '53', '54', '55',
'56', '57', '58', '59', '60')
second.set(seconds[0])

secs = OptionMenu(frame, second, *seconds)


secs.pack(side=LEFT)

Button(root,text="Set Alarm",font=("Helvetica 15"),command=Threading).pack(pady=20)

# Execute Tkinter
root.mainloop()
Output:

11.Basic Web Scraper: Write a web scraper that extracts data from a website
of interest. You can use libraries like BeautifulSoup and requests for this task.
Program to write web Scaper:

13. Expense Tracker: Develop a program that helps users track their daily
expenses.Users should be able to add expenses, categorize them, and view
summaries.
Program to write expense tracker:

14.Word Counter: Create a program that counts the number of words


characters, and lines in a text document.
# Python code to demonstrate
# to count words in string using reduce

from functools import reduce

# initializing string
test_string = "python programming is simple and can be easy to understand"

# printing original string


print("The original string is : " + test_string)

# to count words in string using reduce


res = reduce(lambda x, y: x + 1 if y == ' ' else x, test_string, 1)

# printing result
print("The number of words in string are : " + str(res))

Output:
The original string is : python programming is simple and can be easy to understand
The number of words in string are : 10

15.Password Manager: Design a password manager that securely stores and


retrieves passwords for different accounts. Use encryption to protect
sensitive data
Python program to manage paswords:
import tkinter as tk
from tkinter import messagebox

def add():
# accepting input from the user
username = entryName.get()
# accepting password input from the user
password = entryPassword.get()
if username and password:
with open("passwords.txt", 'a') as f:
f.write(f"{username} {password}\n")
messagebox.showinfo("Success", "Password added !!")
else:
messagebox.showerror("Error", "Please enter both the fields")
def get():
# accepting input from the user
username = entryName.get()

# creating a dictionary to store the data in the form of key-value pairs


passwords = {}
try:
# opening the text file
with open("passwords.txt", 'r') as f:
for k in f:
i = k.split(' ')
# creating the key-value pair of username and password.
passwords[i[0]] = i[1]
except:
# displaying the error message
print("ERROR !!")

if passwords:
mess = "Your passwords:\n"
for i in passwords:
if i == username:
mess += f"Password for {username} is {passwords[i]}\n"
break
else:
mess += "No Such Username Exists !!"
messagebox.showinfo("Passwords", mess)
else:
messagebox.showinfo("Passwords", "EMPTY LIST!!")
def delete():
# accepting input from the user
username = entryName.get()

# creating a temporary list to store the data


temp_passwords = []
# reading data from the file and excluding the specified username
try:
with open("passwords.txt", 'r') as f:
for k in f:
i = k.split(' ')
if i[0] != username:
temp_passwords.append(f"{i[0]} {i[1]}")

# writing the modified data back to the file


with open("passwords.txt", 'w') as f:
for line in temp_passwords:
f.write(line)

messagebox.showinfo(
"Success", f"User {username} deleted successfully!")
except Exception as e:
messagebox.showerror("Error", f"Error deleting user {username}: {e}")
if __name__ == "__main__":
app = tk.Tk()
app.geometry("560x270")
app.title("Password Manager")

# Username block
labelName = tk.Label(app, text="USERNAME:")
labelName.grid(row=0, column=0, padx=15, pady=15)
entryName = tk.Entry(app)
entryName.grid(row=0, column=1, padx=15, pady=15)

# Password block
labelPassword = tk.Label(app, text="PASSWORD:")
labelPassword.grid(row=1, column=0, padx=10, pady=5)
entryPassword = tk.Entry(app)
entryPassword.grid(row=1, column=1, padx=10, pady=5)

# Add button
buttonAdd = tk.Button(app, text="Add", command=add)
buttonAdd.grid(row=2, column=0, padx=15, pady=8, sticky="we")

# Get button
buttonGet = tk.Button(app, text="Get", command=get)
buttonGet.grid(row=2, column=1, padx=15, pady=8, sticky="we")

# List Button
buttonList = tk.Button(app, text="List", command=getlist)
buttonList.grid(row=3, column=0, padx=15, pady=8, sticky="we")

# Delete button
buttonDelete = tk.Button(app, text="Delete", command=delete)
buttonDelete.grid(row=3, column=1, padx=15, pady=8, sticky="we")

app.mainloop()
output:

You might also like