0% found this document useful (0 votes)
2 views5 pages

Python 1

The document outlines three programming tasks: a tax calculator that determines tax rates based on salary, a dictionary mapping word lengths from a list, and an object-oriented chat system with user and message management. Each task includes code snippets demonstrating the implementation and functionality. The chat system allows users to join, leave, send messages, and view chat history.
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)
2 views5 pages

Python 1

The document outlines three programming tasks: a tax calculator that determines tax rates based on salary, a dictionary mapping word lengths from a list, and an object-oriented chat system with user and message management. Each task includes code snippets demonstrating the implementation and functionality. The chat system allows users to join, leave, send messages, and view chat history.
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

Task 1: Tax Calculator using Conditional Statements

This program takes the salary as input, determines the appropriate tax rate based on the rules
in [Link], and calculates the final tax amount.

# Task 1: Tax Calculation Program

try:
# Taking salary as input from the user
salary = float(input("Enter the salary amount: "))

# Applying conditional statements based on the rules


if salary < 30000:
tax_rate = 0.05 # 5%
elif 30000 <= salary <= 70000:
tax_rate = 0.15 # 15%
else:
tax_rate = 0.25 # 25%

# Calculating the final tax


final_tax = salary * tax_rate

# Displaying the results


print(f"\n--- Tax Calculation Result ---")
print(f"Salary: {salary:,.2f}")
print(f"Applied Tax Rate: {tax_rate * 100}%")
print(f"Final Tax Amount: {final_tax:,.2f}")

except ValueError:
print("Please enter a valid numeric value for salary.")

Task 2: Word Length Dictionary Mapping


This script takes the provided list of words and uses a dictionary comprehension to map each
word to its character length, matching the exact format shown in [Link].

# Task 2: Dictionary Mapping Word Lengths

# Given list of words


words = ["apple", "banana", "kiwi", "cherry", "mango"]
# Creating a dictionary using a dictionary comprehension
word_lengths = {word: len(word) for word in words}

# Displaying the final output


print("Output:")
print(word_lengths)

Task 3: OOP-Based Chat System


This solution implements a basic Object-Oriented Programming structure with User, Message,
and ChatRoom classes, handling joining, leaving, sending messages, and viewing history.

# Task 3: Object-Oriented Chat System

from datetime import datetime

class User:

def __init__(self, username):

[Link] = username

def __str__(self):

return [Link]

class Message:

def __init__(self, sender, content):

[Link] = sender # Expects a User object

[Link] = content
[Link] = [Link]().strftime("%H:%M:%S")

def __str__(self):

return f"[{[Link]}] {[Link]}: {[Link]}"

class ChatRoom:

def __init__(self, room_name):

self.room_name = room_name

self.active_users = {} # Keeps track of users currently in the room

self.chat_history = [] # Stores Message objects

def join_room(self, user):

if [Link] not in self.active_users:

self.active_users[[Link]] = user

print(f"🚪 {[Link]} has joined the chat room '{self.room_name}'.")

else:

print(f"{[Link]} is already in the room.")

def leave_room(self, user):

if [Link] in self.active_users:

del self.active_users[[Link]]

print(f"🚶 {[Link]} has left the chat room '{self.room_name}'.")

else:

print(f"{[Link]} is not currently in this chat room.")


def send_message(self, user, content):

# Verify if the user belongs to the room before allowing them to text

if [Link] in self.active_users:

new_msg = Message(user, content)

self.chat_history.append(new_msg)

else:

print(f"❌ Denied: {[Link]} must join the room before sending a message.")

def view_history(self):

print(f"\n--- Chat History for '{self.room_name}' ---")

if not self.chat_history:

print("(No messages yet)")

else:

for msg in self.chat_history:

print(msg)

print("-" * 35)

# --- Demonstrating the Chat System Functionalities ---

if __name__ == "__main__":

# 1. Create a ChatRoom

my_room = ChatRoom("Python Developers")

# 2. Create Users

user1 = User("Ali")
user2 = User("Sana")

# 3. Users joining the room

my_room.join_room(user1)

my_room.join_room(user2)

print()

# 4. Sending messages

my_room.send_message(user1, "Hello everyone! Welcome to the group.")

my_room.send_message(user2, "Hi Ali! Glad to be here.")

my_room.send_message(user1, "Let's complete this assignment using OOP.")

# 5. Viewing chat history

my_room.view_history()

# 6. User leaving the room

print()

my_room.leave_room(user2)

# Attempting to send a message after leaving

my_room.send_message(user2, "Can you guys still hear me?")

You might also like