[go: up one dir, main page]

0% found this document useful (0 votes)
6 views15 pages

Python Tast

Uploaded by

nicholasyu040906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views15 pages

Python Tast

Uploaded by

nicholasyu040906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Question 1

1)

# Hair salon

# Student: yu

# Date: 12 June 2025

class Product:

def __init__(self, name, price, quantity, category):

self.name = name

self.price = price

self.quantity = quantity

self.category = category

def __str__(self):

return f"{self.name} - R{self.price} ({self.quantity} left)"

2. class Inventory:

def __init__(self):

self.products = []

def add_product(“self, product”):

self.products.append(“product”)

print(f"Added: {product.name}")

def update_product(self, name, new_price=None, new_quantity=None):

for product in self.products:

if product.name == name:
if new_price:

product.price = new_price

if new_quantity:

product.quantity = new_quantity

print(f"Updated {name}")

return

print(f"{name} not found")

def show_products(self):

print("\Hair.solon:")

for product in self.products:

print(product)

def find_product(self, name):

for product in self.products:

if product.name == name:

return product

return None

def total_value(self):

return sum(product.price * product.quantity for product in self.products)

3.) # Main program

if __name__ == "__main__":

shop = Inventory()
# Add products

shop.add_product(Product("asian Shampoo", 78.99, 12, "Hair Care"))

shop.add_product(Product("Asian Conditioner", 78.99, 8, "Hair Care"))

shop.add_product(Product("asian hair growth", 200, 5, "Treatment"))

shop.add_product(Product("asian hair powder", 249.99, 15, "Styling"))

# Show all products

shop.show_products()

# Update a product

shop.update_product("Asian conditioner", new_price=125.00)

# Find a product

found = shop.find_product("Asian hair growth")

if found:

print(f"\nFound product: {found}")

else:

print("\nProduct not found")

# Calculate total value

print(f"\nTotal inventory value: R{shop.total_value():.2f}")


Question 2

# Todo List Application

# Student: yu

# Date:12 June 2025

import tkinter as tk

from tkinter import messagebox

class MustDoApp:

def __init__(self, root):

self.root = root

self.root.title("Hair solon")

self.root.geometry("400x400")

# Create widgets

self.task_entry = tk.Entry(root, width=40, font=('Arial', 12))

self.add_button = tk.Button(root, text="Add Task", command=self.add_task, bg='#4CAF50',


fg='white')

self.task_listbox = tk.Listbox(root, width=50, height=15, font=('Arial', 11))

self.remove_button = tk.Button(root, text="Remove Task", command=self.remove_task,


bg='#f44336', fg='white')

# Layout widgets

self.task_entry.pack(pady=10)

self.add_button.pack(pady=5)

self.task_listbox.pack(pady=10)
self.remove_button.pack(pady=5)

# Sample tasks (optional)

self.sample_tasks = [

"Check stock",

"Order new Asian hair power stock",

"Schedule social media posts",

"Update product pricing"

for task in self.sample_tasks:

self.task_listbox.insert(tk.END, task)

def add_task(self):

"""Adds task from entry box to listbox"""

task = self.task_entry.get()

if task.strip() == "":

messagebox.showwarning("Warning", "Please enter a task")

return

self.task_listbox.insert(tk.END, task)

self.task_entry.delete(0, tk.END) # Clear entry box

def remove_task(self):

"""Removes selected task from listbox"""

try:
selected_index = self.task_listbox.curselection()[0]

self.task_listbox.delete(selected_index)

except IndexError:

messagebox.showwarning("Warning", "Please select a task to remove")

# Main program

if __name__ == "__main__":

root = tk.Tk()

app = TodoApp(root)

root.mainloop()

Question 3

# Eduvos Library System

# Student: yu

# Date: 12 June 2025

class Book:

def __init__(self, title, author, isbn):

self.title = title

self.author = author

self.isbn = isbn

self.is_borrowed = False

def __str__(self):

status = "Available" if not self.is_borrowed else "Borrowed"

return f"'{self.title}' by {self.author} ({status})"


class Patron:

def __init__(self, name, patron_id):

self.name = name

self.patron_id = patron_id

self.borrowed_books = []

def borrow_book(self, book):

if not book.is_borrowed:

self.borrowed_books.append(book)

book.is_borrowed = True

print(f"{self.name} borrowed {book.title}")

else:

print(f"Book '{book.title}' is not available")

def return_book(self, book):

if book in self.borrowed_books:

self.borrowed_books.remove(book)

book.is_borrowed = False

print(f"{self.name} returned {book.title}")

else:

print(f"{self.name} doesn't have this book")

def show_borrowed(self):

if not self.borrowed_books:

print(f"{self.name} has no books")

else:
print(f"\n{self.name}'s books:")

for book in self.borrowed_books:

print(f"- {book.title}")

class Library:

def __init__(self):

self.books = []

self.patrons = []

def add_book(self, title, author, isbn):

new_book = Book(title, author, isbn)

self.books.append(new_book)

print(f"Added book: {title}")

def register_patron(self, name, patron_id):

new_patron = Patron(name, patron_id)

self.patrons.append(new_patron)

print(f"Registered {name}")

def borrow_book(self, patron_id, isbn):

patron = next((p for p in self.patrons if p.patron_id == patron_id), None)

book = next((b for b in self.books if b.isbn == isbn), None)

if patron and book:

patron.borrow_book(book)

else:
print("Error: Patron or book not found")

def return_book(self, patron_id, isbn):

patron = next((p for p in self.patrons if p.patron_id == patron_id), None)

book = next((b for b in self.books if b.isbn == isbn), None)

if patron and book:

patron.return_book(book)

else:

print("Error: Patron or book not found")

def show_available(self):

available = [b for b in self.books if not b.is_borrowed]

print("\nAvailable books:")

for book in available:

print(f"- {book}")

# Main program

if __name__ == "__main__":

lib = Library()

# Add South African books

lib.add_book("Disgrace", "J.M. Coetzee", "9780099289524")

lib.add_book("long walk to freedom", "Nelson Mandela", "978031658182")

lib.add_book("The Cry of Winnie Mandela", "Njabulo Ndebele", "978177014006")


# Register members

lib.register_patron("Max Stuart", "PAT001")

lib.register_patron("Alex Rou", "PAT002")

# Demonstrate operations

print("\n=== Library Operations ===")

lib.borrow_book("PAT001", "978039958807") # Max borrows book

lib.borrow_book("PAT002", "978009951121") # Alex borrows book

# Show status

next(p for p in lib.patrons if p.patron_id == "PAT001").show_borrowed()

lib.show_available()

# Return book

print("\n=== Returning book ===")

lib.return_book("PAT001", "978039958807")

lib.show_available()
Question 4

# Task Management System

# Student: Yu

# Date: 12 July 2025

class Task:

def __init__(self, title, description):

self.title = title

self.description = description

self.is_completed = False

def mark_complete(self):

self.is_completed = True

def __str__(self):

status = "Completed" if self.is_completed else "Pending"

return f"{self.title} - {self.description} [{status}]"

class TaskManager:

def __init__(self):

self.tasks = []

def add_task(self, title, description):

new_task = Task(title, description)

self.tasks.append(new_task)

print(f'Added: "{title}"')
def complete_task(self, title):

found = False

for task in self.tasks:

if task.title.lower() == title.lower():

found = True

if task.is_completed:

print(f'"{task.title}" is already completed')

else:

task.mark_complete()

print(f'Completed: "{task.title}"')

break

if not found:

print(f'Task "{title}" not found')

def display_tasks(self):

if not self.tasks:

print("No tasks available")

return

print("\nYOUR TASKS:")

print("-----------")

for i, task in enumerate(self.tasks, 1):

print(f"{i}. {task}")

# Main program
if __name__ == "__main__":

print("Yu Task Manager")

print("------------------------")

my_tasks = TaskManager()

# Add initial tasks

my_tasks.add_task("Buy groceries", "oil, bread, bacon")

my_tasks.add_task("update work", "complete python task")

# Show all tasks

my_tasks.display_tasks()

# Complete a task

print("\nCompleting task:")

my_tasks.complete_task("buy groceries")

# Show updated list

print("\nUpdated tasks:")

my_tasks.display_tasks()

You might also like