├── README.md ├── backdate_commit.sh ├── calculator.py ├── classes.py ├── discount.py ├── errors.py ├── fileHandler.py ├── functions.py ├── lists.py ├── myworld.py ├── readAndManage.py └── weatherApp.py /README.md: -------------------------------------------------------------------------------- 1 | # **Python Learning Repository** 2 | 3 | *StephenLegacy* 4 | 5 | Welcome to my **Python Learning Repository - partly powered by Power Learn Project**, where I explore **core concepts, object-oriented programming, and error handling** through practical examples and organized scripts. 🚀 6 | 7 | ## 📂 **Repository Contents** 8 | 9 | - **README.md** – Documentation and project overview. 10 | - **classes.py** – Demonstrates **Python classes, OOP principles, and inheritance**. 11 | - **functions.py** – Covers **functions, arguments, and return values**. 12 | - **errors.py** – Showcases **error handling and exception management**. 13 | - **calculator.py** – Power Learn Project week 1 Python **Assignment**. 14 | - **lists.py** – Power Learn Project week 2 Python **Assignment**. 15 | - **discount.py** – Power Learn Project week 3 Python **Assignment**. 16 | - **fileHandler.py** – Power Learn Project week 4 Python **Assignment**. 17 | - **readAndManage.py** – Power Learn Project week 3 DATABASE == Python **Assignment**. 18 | - **weatherApp.py** – KEEP THE BUILDING SPIRIT == Python **JAMS**. 19 | - **myworld.py** – Power Learn Project Week 5 Python || Classes & OOP **Assignment**. 20 | 21 | ## 🎯 **Purpose** 22 | This repository is a **learning hub** for Python begiinings, focusing on **clean coding practices, structured programming, and problem-solving**. 23 | 24 | ## 💡 **How to Use** 25 | Clone the repo, explore the scripts, and modify them for **practice and experimentation**. Contributions and improvements are highly welcome, This is a learning process. 26 | 27 | 📌 **GitHub**: [StephenLegacy](https://github.com/StephenLegacy) 🚀 28 | -------------------------------------------------------------------------------- /backdate_commit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Set the backdate (yesterday's date) 4 | BACKDATE="2025-04-18T11:32:00" 5 | 6 | # Add and commit each file separately 7 | git add backdate_commit.sh 8 | GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Add comment functionality (backdated --W0o0w!)" 9 | 10 | # git add add_comment.php 11 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Add comment functionality " 12 | 13 | # git add add_post.php 14 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Implement post creation feature (backdated)" 15 | 16 | # git add admin.css 17 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Style improvements for admin panel (backdated)" 18 | 19 | # git add admin.php 20 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Build admin dashboard functionality (backdated)" 21 | 22 | # git add admin_login.php 23 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Implement admin login system (backdated)" 24 | 25 | # git add database.sqlite 26 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Update SQLite database (backdated)" 27 | 28 | # git add db.php 29 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Database connection and queries (backdated)" 30 | 31 | # git add edit_post.php 32 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Enable post editing (backdated)" 33 | 34 | # git add global.css 35 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Global styles for consistency (backdated)" 36 | 37 | # git add index.php 38 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Homepage with posts and pagination (backdated)" 39 | 40 | # git add login.php 41 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "User login implementation (backdated)" 42 | 43 | # git add logout.php 44 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Logout system added (backdated)" 45 | 46 | # git add profile_pictures/ 47 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Profile pictures storage (backdated)" 48 | 49 | # git add reg.css 50 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Styles for registration page (backdated)" 51 | 52 | # git add register.php 53 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "User registration system (backdated)" 54 | 55 | # git add style.css 56 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "General website styles (backdated)" 57 | 58 | # git add uploads/ 59 | # GIT_AUTHOR_DATE="$BACKDATE" GIT_COMMITTER_DATE="$BACKDATE" git commit -m "Media upload folder (backdated)" 60 | 61 | # Push all commits 62 | git push origin main # Change 'main' to your branch name if different -- wahala 63 | -------------------------------------------------------------------------------- /calculator.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import ttk 3 | 4 | # Evaluate the expression 5 | def calculate(): 6 | try: 7 | result.set(eval(expression.get())) 8 | except Exception: 9 | result.set("Error") 10 | 11 | # Add characters to the expression for calculator 12 | def press(key): 13 | expression.set(expression.get() + str(key)) 14 | 15 | # Clear the entire input 16 | def clear(): 17 | expression.set("") 18 | result.set("") 19 | 20 | # Delete the last character 21 | def delete(): 22 | expression.set(expression.get()[:-1]) 23 | 24 | # Main window setup 25 | root = tk.Tk() 26 | root.title(" Python Calculator | STEPHEN OLOO ") 27 | root.geometry("400x600") 28 | root.config(bg="#1e1e1e") 29 | 30 | expression = tk.StringVar() 31 | result = tk.StringVar() 32 | 33 | # Expression entry field 34 | entry = ttk.Entry(root, textvariable=expression, font=('Arial', 28)) 35 | entry.pack(fill='both', padx=10, pady=20, ipady=10) 36 | 37 | # Result display 38 | result_label = ttk.Label(root, textvariable=result, font=('Arial', 24), background="#1e1e1e", foreground="#00FF00") 39 | result_label.pack(fill='both', padx=10) 40 | 41 | # Button layout 42 | buttons = [ 43 | ['7', '8', '9', '/'], 44 | ['4', '5', '6', '*'], 45 | ['1', '2', '3', '-'], 46 | ['0', '.', '⌫', '+'], 47 | ] 48 | 49 | frame = tk.Frame(root, bg="#1e1e1e") 50 | frame.pack() 51 | 52 | # Create buttons dynamically 53 | for row in buttons: 54 | row_frame = tk.Frame(frame, bg="#1e1e1e") 55 | row_frame.pack(expand=True, fill='both') 56 | for btn in row: 57 | if btn == '⌫': 58 | action = delete 59 | else: 60 | action = lambda x=btn: press(x) 61 | tk.Button(row_frame, text=btn, font=('Arial', 20), command=action, bg="#333", fg="white", width=5, height=2).pack(side='left', expand=True, fill='both') 62 | 63 | # Control buttons (Clear and Equal) 64 | control_frame = tk.Frame(root, bg="#1e1e1e") 65 | control_frame.pack(expand=True, fill='both', padx=10, pady=10) 66 | 67 | tk.Button(control_frame, text='C', font=('Arial', 24), command=clear, bg="#ff4d4d", fg="white").pack(side='left', expand=True, fill='both', padx=5) 68 | tk.Button(control_frame, text='=', font=('Arial', 24), command=calculate, bg="#00bfff", fg="white").pack(side='left', expand=True, fill='both', padx=5) 69 | 70 | root.mainloop() 71 | -------------------------------------------------------------------------------- /classes.py: -------------------------------------------------------------------------------- 1 | '''Classes: Blueprints for objects. 2 | Objects: Instances of a class. 3 | Attributes and Methods: Define object properties and behaviors. 4 | OOP Principles: Encapsulation, Inheritance, Polymorphism, and Abstraction. 5 | Special Methods: __init__, __str__, __repr__, etc., provide custom behavior.''' 6 | 7 | # Defining a class named `car` (Classes are blueprints for creating objects) 8 | 9 | class Person: 10 | pass # A placeholder indicating no implementation yet, This basically allows a blank class without errors 11 | 12 | class car: 13 | # The constructor method (__init__) initializes object attributes when an instance of the class is created 14 | def __init__(self, hp, model, brand, year): 15 | self.horsepower = hp # Assigning `hp` to the instance attribute `horsepower` 16 | self.model = model 17 | self.brand = brand 18 | self.year = year 19 | self.date = date 20 | 21 | # Defining a method to return information about the car 22 | # This is an instance method because it works on an instance of the class 23 | 24 | def info(self): 25 | return f'{self.horsepower} HP {self.model} {self.brand} {self.year}' 26 | # Returns a formatted string with the car's details 27 | 28 | # Creating instances (objects) of the `car` class 29 | car1 = car(855, "AudiGT", "AUDI", 2024) 30 | car2 = car(478, "AudiGT", "AUDI", 2025) 31 | car3 = car(458, "AudiGT", "AUDI", 2023) 32 | 33 | # Printing information about the cars using the `info()` method 34 | print(car1.info()) 35 | print(car2.info()) 36 | 37 | #Inheritance: A class can copy attributes and methods from another class. 38 | 39 | class ElectricCar(car): # ElectricCar inherits from car 40 | def __init__(self, hp, model, brand, year, battery_size): 41 | super().__init__(hp, model, brand, year) # Call parent class's constructor 42 | self.battery_size = battery_size # New attribute for ElectricCar 43 | 44 | def battery_info(self): 45 | return f"Battery size: {self.battery_size} kWh" 46 | 47 | ecar = ElectricCar(500, "Model S", "Tesla", 2024, 100) 48 | print(ecar.info()) # Inherited method 49 | print(ecar.battery_info()) # Specific to ElectricCar 50 | 51 | 52 | #polymorphism : The ability to redefine methods in child classes. 53 | 54 | class Car: 55 | def drive(self): 56 | return "The car is driving." 57 | 58 | class SportsCar(Car): 59 | def drive(self): 60 | return "The sports car is driving at high speed!" 61 | 62 | car = Car() 63 | sports_car = SportsCar() 64 | print(car.drive()) # Output: The car is driving. this is the parent class 65 | print(sports_car.drive()) # Output: The sports car is driving at high speed! we have copied the method from the parent class 66 | 67 | 68 | #ABSTRACION: Hiding unnecessary implementation details from the users 69 | from abc import ABC, abstractmethod 70 | 71 | class Vehicle(ABC): # Abstract base class 72 | @abstractmethod 73 | def start_engine(self): 74 | pass # No implementation 75 | 76 | class Car(Vehicle): 77 | def start_engine(self): 78 | return "Car engine started." 79 | 80 | my_car = Car() 81 | print(my_car.start_engine()) # Output: Car engine started. 82 | 83 | 84 | #CLASS METHODS: -- Methods that operate on the class rather than an instance. 85 | class Car: 86 | total_cars = 0 # Class attribute 87 | 88 | def __init__(self): 89 | Car.total_cars += 1 90 | 91 | @classmethod 92 | def car_count(cls): 93 | return f"Total cars created: {cls.total_cars}" 94 | 95 | car1 = Car() 96 | car2 = Car() 97 | print(Car.car_count()) # Output: Total cars created: 2 98 | 99 | -------------------------------------------------------------------------------- /discount.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import messagebox 3 | import pygame 4 | import threading 5 | import time 6 | 7 | # Initialize pygame for audio feedback 8 | pygame.mixer.init() 9 | 10 | def play_sound(): 11 | try: 12 | sound = pygame.mixer.Sound("alert.wav") # Ensure you have an alert.wav file in the same directory 13 | sound.play() 14 | time.sleep(30) # Allow sound to play for 30 seconds 15 | sound.stop() 16 | except pygame.error: 17 | messagebox.showwarning("Audio Error", "Unable to play sound. Check the file format.") 18 | 19 | def calculate_discount(price, discount_percent): 20 | if discount_percent >= 20: 21 | discount_amount = (discount_percent / 100) * price 22 | return price - discount_amount 23 | return price 24 | 25 | def calculate_and_display(): 26 | try: 27 | price = float(price_entry.get()) # Get the entered price and convert to float 28 | discount = float(discount_entry.get()) # Get the discount percentage and convert to float 29 | final_price = calculate_discount(price, discount) # Calculate the final price 30 | threading.Thread(target=play_sound).start() # Play alert sound in a separate thread 31 | messagebox.showinfo("Final Price", f"Final price after discount: ${final_price:.2f}") # Display the final price 32 | except ValueError: 33 | messagebox.showerror("Input Error", "Enter valid numbers for price and discount.") # Show error for invalid input 34 | 35 | # Create the main application window 36 | app = tk.Tk() 37 | app.title("Discount Calculator") # Set window title 38 | app.geometry("500x400") # Set window size 39 | app.configure(bg="#1e1e2d") # Set background color 40 | 41 | # Label and input field for original price 42 | label1 = tk.Label(app, text="Original Price:", fg="white", bg="#1e1e2d", font=("Arial", 14)) 43 | label1.pack(pady=10) 44 | price_entry = tk.Entry(app, font=("Arial", 14)) 45 | price_entry.pack() 46 | 47 | # Label and input field for discount percentage 48 | label2 = tk.Label(app, text="Discount Percentage:", fg="white", bg="#1e1e2d", font=("Arial", 14)) 49 | label2.pack(pady=10) 50 | discount_entry = tk.Entry(app, font=("Arial", 14)) 51 | discount_entry.pack() 52 | 53 | # Button to calculate discount 54 | calculate_button = tk.Button(app, text="Calculate", command=calculate_and_display, font=("Arial", 14), bg="#e74c3c", fg="white", padx=15, pady=5) 55 | calculate_button.pack(pady=20) 56 | 57 | # Button to close the application 58 | close_button = tk.Button(app, text="Exit", command=app.quit, font=("Arial", 14), bg="#d35400", fg="white", padx=15, pady=5) 59 | close_button.pack(pady=10) 60 | 61 | # Run the main event loop 62 | app.mainloop() 63 | -------------------------------------------------------------------------------- /errors.py: -------------------------------------------------------------------------------- 1 | #THIS BASICALL HAS EVERYTHING ABOUT ERROR HANDLING 2 | try: 3 | print(x) 4 | except: 5 | print("Error, X is not defined") 6 | else: 7 | print("There are no errors") 8 | finally: 9 | print("The 'ty - except' is finished" ) 10 | 11 | import logging 12 | 13 | # Setting up logging for error tracking 14 | logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s') 15 | 16 | # Custom exception class 17 | class CustomError(Exception): 18 | def __init__(self, message): 19 | self.message = message 20 | 21 | # Function demonstrating multiple exception handling and raising exceptions 22 | def divide_numbers(a, b): 23 | try: 24 | if b == 0: 25 | raise ZeroDivisionError("You can't divide by zero!") # Explicitly raise an exception 26 | return a / b 27 | except ZeroDivisionError as e: 28 | print(f"Error: {e}") 29 | logging.error(e) 30 | except TypeError as e: 31 | print("Error: Inputs must be numbers.") 32 | logging.error(e) 33 | else: 34 | print("Division successful!") # Executes if no exception occurs 35 | finally: 36 | print("Division attempt completed.") # Always executes 37 | 38 | # Function demonstrating file operations with error handling 39 | def read_file(filename): 40 | try: 41 | with open(filename, "r") as file: 42 | return file.read() 43 | except FileNotFoundError: 44 | print(f"The file '{filename}' does not exist.") 45 | except PermissionError: 46 | print(f"Permission denied for file '{filename}'.") 47 | else: 48 | print("File read successfully!") 49 | finally: 50 | print("File operation completed.") 51 | 52 | # Main code block to demonstrate all features 53 | if __name__ == "__main__": 54 | print("=== Division Example ===") 55 | divide_numbers(10, 0) # Triggers ZeroDivisionError 56 | divide_numbers(10, "5") # Triggers TypeError 57 | print(divide_numbers(10, 2)) # Valid division 58 | 59 | print("\n=== File Handling Example ===") 60 | read_file("non_existent_file.txt") # Triggers FileNotFoundError 61 | read_file("example.txt") # Replace with an existing file to see successful read 62 | 63 | print("\n=== Custom Exception Example ===") 64 | try: 65 | raise CustomError("This is a custom error!") # Raising a custom exception 66 | except CustomError as e: 67 | print(f"Caught a custom error: {e.message}") 68 | 69 | print("\n=== Logging Example ===") 70 | try: 71 | risky_code = 10 / 0 # Intentional error for logging 72 | except ZeroDivisionError as e: 73 | logging.error(f"Caught an error during risky operation: {e}") 74 | print("Logged the error.") 75 | -------------------------------------------------------------------------------- /fileHandler.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import filedialog, messagebox, scrolledtext 3 | import os 4 | 5 | # Function to create input.txt and allow editing 6 | def create_default_file(): 7 | if not os.path.exists("input.txt"): # Check if input.txt exists 8 | with open("input.txt", "w") as f: 9 | f.write("This is a sample text file.\nIt contains multiple lines.\nPython is amazing!\nFile handling is fun.\nLet's process this file.") 10 | open_file("input.txt") 11 | 12 | # Function to open a file and allow editing 13 | def open_file(filename=None): 14 | if filename is None: 15 | filename = filedialog.askopenfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]) 16 | if not filename: 17 | return 18 | 19 | text_area.delete(1.0, tk.END) # Clear previous text 20 | with open(filename, "r") as file: 21 | text_area.insert(tk.END, file.read()) 22 | root.title(f"Editing - {os.path.basename(filename)}") 23 | save_button.config(state=tk.NORMAL) # Enable saving 24 | process_button.config(state=tk.NORMAL) 25 | global current_file 26 | current_file = filename 27 | 28 | # Function to save the edited file 29 | def save_file(): 30 | if current_file: 31 | with open(current_file, "w") as file: 32 | file.write(text_area.get(1.0, tk.END)) 33 | messagebox.showinfo("Success", f"File '{current_file}' saved successfully!") 34 | 35 | # Function to process the text file 36 | def process_file(): 37 | if not current_file: 38 | messagebox.showwarning("Warning", "No file opened to process!") 39 | return 40 | 41 | with open(current_file, "r") as file: 42 | content = file.read() 43 | word_count = len(content.split()) 44 | uppercase_text = content.upper() 45 | 46 | output_file = "output.txt" 47 | with open(output_file, "w") as file: 48 | file.write(uppercase_text + f"\n\nWord Count: {word_count}") 49 | 50 | messagebox.showinfo("Success", f"Processed file saved as '{output_file}' with word count: {word_count}") 51 | open_file(output_file) # Open processed file for review 52 | 53 | # Function to exit the application 54 | def exit_app(): 55 | if messagebox.askyesno("Exit", "Are you sure you want to quit?"): 56 | root.destroy() 57 | 58 | # GUI Setup 59 | root = tk.Tk() 60 | root.title("Text File Processor") 61 | root.geometry("600x500") 62 | root.configure(bg="#f0f0f0") 63 | root.resizable(False, False) 64 | 65 | current_file = None # Track the currently opened file 66 | 67 | frame = tk.Frame(root, bg="#ffffff", padx=10, pady=10, relief=tk.RAISED, bd=5) 68 | frame.pack(pady=10) 69 | 70 | text_area = scrolledtext.ScrolledText(frame, wrap=tk.WORD, width=60, height=15, font=("Arial", 12), bd=2, relief=tk.GROOVE) 71 | text_area.pack() 72 | 73 | button_frame = tk.Frame(root, bg="#f0f0f0") 74 | button_frame.pack(pady=10) 75 | 76 | create_button = tk.Button(button_frame, text="Create Input File", command=create_default_file, bg="#4CAF50", fg="white", font=("Arial", 10, "bold"), padx=10, pady=5, relief=tk.GROOVE) 77 | create_button.grid(row=0, column=0, padx=5) 78 | 79 | open_button = tk.Button(button_frame, text="Open File", command=open_file, bg="#2196F3", fg="white", font=("Arial", 10, "bold"), padx=10, pady=5, relief=tk.GROOVE) 80 | open_button.grid(row=0, column=1, padx=5) 81 | 82 | save_button = tk.Button(button_frame, text="Save File", command=save_file, bg="#FF9800", fg="white", font=("Arial", 10, "bold"), padx=10, pady=5, relief=tk.GROOVE, state=tk.DISABLED) 83 | save_button.grid(row=0, column=2, padx=5) 84 | 85 | process_button = tk.Button(button_frame, text="Process File", command=process_file, bg="#9C27B0", fg="white", font=("Arial", 10, "bold"), padx=10, pady=5, relief=tk.GROOVE, state=tk.DISABLED) 86 | process_button.grid(row=0, column=3, padx=5) 87 | 88 | exit_button = tk.Button(root, text="Exit", command=exit_app, bg="#F44336", fg="white", font=("Arial", 10, "bold"), padx=10, pady=5, relief=tk.GROOVE) 89 | exit_button.pack(pady=5) 90 | 91 | create_default_file() # Start with input.txt 92 | root.mainloop() 93 | -------------------------------------------------------------------------------- /functions.py: -------------------------------------------------------------------------------- 1 | def myfunc( name, *args): #argument 1 2 | print(f" Hello {name}") 3 | 4 | for x in args: 5 | print(f"Hello {x}") 6 | 7 | myfunc("Oloo", "Stephen", "James") 8 | 9 | 10 | -------------------------------------------------------------------------------- /lists.py: -------------------------------------------------------------------------------- 1 | # Step 1: Create an empty list 2 | my_list = [] 3 | 4 | # Step 2: Append elements 10, 20, 30, 40 5 | my_list.append(10) 6 | my_list.append(20) 7 | my_list.append(30) 8 | my_list.append(40) 9 | 10 | # Step 3: Insert 15 at the second position (index 1) 11 | my_list.insert(1, 15) 12 | 13 | # Step 4: Extend my_list with [50, 60, 70] 14 | my_list.extend([50, 60, 70]) 15 | 16 | # Step 5: Remove the last element from my_list 17 | my_list.pop() 18 | 19 | # Step 6: Sort my_list in ascending order 20 | my_list.sort() 21 | 22 | # Step 7: Find and print the index of value 30 23 | index_of_30 = my_list.index(30) 24 | 25 | # Print the final list and index of 30 26 | print("Final List:", my_list) 27 | print("Index of 30:", index_of_30) 28 | -------------------------------------------------------------------------------- /myworld.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import ttk, messagebox 3 | 4 | # ------------------ Classes (OOP Part) ------------------ 5 | class Smartphone: 6 | def __init__(self, brand, model, storage): 7 | self.brand = brand 8 | self.model = model 9 | self.storage = storage 10 | self.is_on = False 11 | 12 | def power_on(self): 13 | self.is_on = True 14 | return f"{self.model} is now ON 🔋" 15 | 16 | def power_off(self): 17 | self.is_on = False 18 | return f"{self.model} is now OFF 📴" 19 | 20 | def specs(self): 21 | return f"📱 {self.brand} {self.model} - {self.storage}GB" 22 | 23 | class SmartPhonePro(Smartphone): 24 | def __init__(self, brand, model, storage, stylus_support): 25 | super().__init__(brand, model, storage) 26 | self.stylus_support = stylus_support 27 | 28 | def show_pro_features(self): 29 | return f"🆕 {self.model} Pro supports stylus: {self.stylus_support}" 30 | 31 | class Vehicle: 32 | def move(self): 33 | return "The vehicle moves" 34 | 35 | class Car(Vehicle): 36 | def move(self): 37 | return "🚗 The car drives on the road." 38 | 39 | class Plane(Vehicle): 40 | def move(self): 41 | return "✈️ The plane flies in the sky." 42 | 43 | class Boat(Vehicle): 44 | def move(self): 45 | return "🚢 The boat sails on the water." 46 | 47 | # ------------------ GUI App ------------------ 48 | class MyWorldApp: 49 | def __init__(self, root): 50 | self.root = root 51 | self.root.title("🌍 MyWorld Simulator") 52 | self.root.geometry("500x400") 53 | 54 | title = tk.Label(root, text="🌍 MyWorld Simulator", font=("Arial", 20)) 55 | title.pack(pady=20) 56 | 57 | # Buttons to navigate 58 | tk.Button(root, text="📱 Smartphone Simulator", width=25, command=self.open_smartphone_window).pack(pady=10) 59 | tk.Button(root, text="🚗 Vehicle Movement Simulator", width=25, command=self.open_vehicle_window).pack(pady=10) 60 | tk.Button(root, text="❌ Exit", width=25, command=root.quit).pack(pady=10) 61 | 62 | # Smartphone Window 63 | def open_smartphone_window(self): 64 | win = tk.Toplevel(self.root) 65 | win.title("📱 Smartphone Creator") 66 | win.geometry("450x450") 67 | 68 | tk.Label(win, text="Smartphone Creator", font=("Arial", 16)).pack(pady=10) 69 | 70 | # Entry fields 71 | brand_var = tk.StringVar() 72 | model_var = tk.StringVar() 73 | storage_var = tk.StringVar() 74 | pro_var = tk.StringVar(value="no") 75 | stylus_var = tk.StringVar(value="no") 76 | 77 | tk.Label(win, text="Brand").pack() 78 | tk.Entry(win, textvariable=brand_var).pack() 79 | 80 | tk.Label(win, text="Model").pack() 81 | tk.Entry(win, textvariable=model_var).pack() 82 | 83 | tk.Label(win, text="Storage (GB)").pack() 84 | tk.Entry(win, textvariable=storage_var).pack() 85 | 86 | tk.Label(win, text="Pro Version? (yes/no)").pack() 87 | tk.Entry(win, textvariable=pro_var).pack() 88 | 89 | tk.Label(win, text="Stylus Support? (yes/no)").pack() 90 | tk.Entry(win, textvariable=stylus_var).pack() 91 | 92 | output_label = tk.Label(win, text="", fg="green", wraplength=400, justify="left") 93 | output_label.pack(pady=10) 94 | 95 | def simulate_phone(): 96 | brand = brand_var.get() 97 | model = model_var.get() 98 | storage = storage_var.get() 99 | is_pro = pro_var.get().lower() == "yes" 100 | 101 | if is_pro: 102 | stylus = stylus_var.get() 103 | phone = SmartPhonePro(brand, model, storage, stylus) 104 | result = ( 105 | phone.specs() + "\n" + 106 | phone.power_on() + "\n" + 107 | phone.show_pro_features() + "\n" + 108 | phone.power_off() 109 | ) 110 | else: 111 | phone = Smartphone(brand, model, storage) 112 | result = ( 113 | phone.specs() + "\n" + 114 | phone.power_on() + "\n" + 115 | phone.power_off() 116 | ) 117 | output_label.config(text=result) 118 | 119 | tk.Button(win, text="Simulate Smartphone", command=simulate_phone).pack(pady=10) 120 | 121 | # Vehicle Window 122 | def open_vehicle_window(self): 123 | win = tk.Toplevel(self.root) 124 | win.title("🚗 Vehicle Movement Simulator") 125 | win.geometry("400x300") 126 | 127 | tk.Label(win, text="Choose Vehicle", font=("Arial", 16)).pack(pady=10) 128 | 129 | vehicle_var = tk.StringVar(value="Car") 130 | vehicle_options = ["Car", "Plane", "Boat"] 131 | 132 | dropdown = ttk.Combobox(win, textvariable=vehicle_var, values=vehicle_options, state="readonly") 133 | dropdown.pack(pady=10) 134 | 135 | output_label = tk.Label(win, text="", font=("Arial", 12), fg="blue") 136 | output_label.pack(pady=20) 137 | 138 | def simulate_movement(): 139 | choice = vehicle_var.get() 140 | if choice == "Car": 141 | v = Car() 142 | elif choice == "Plane": 143 | v = Plane() 144 | else: 145 | v = Boat() 146 | 147 | output_label.config(text=v.move()) 148 | 149 | tk.Button(win, text="Move Vehicle", command=simulate_movement).pack(pady=10) 150 | 151 | # ------------------ Run App ------------------ 152 | if __name__ == "__main__": 153 | root = tk.Tk() 154 | app = MyWorldApp(root) 155 | root.mainloop() 156 | -------------------------------------------------------------------------------- /readAndManage.py: -------------------------------------------------------------------------------- 1 | def read_and_modify_file(): 2 | try: 3 | # Ask the user for a filename 4 | filename = input("Enter the filename to read: ") 5 | 6 | # Attempt to open the file 7 | with open(filename, 'r') as file: 8 | content = file.readlines() 9 | 10 | # Modify content (example: adding line numbers) 11 | modified_content = [f"{i+1}: {line}" for i, line in enumerate(content)] 12 | 13 | # Write to a new file 14 | new_filename = "modified_" + filename 15 | with open(new_filename, 'w') as new_file: 16 | new_file.writelines(modified_content) 17 | 18 | print(f"File has been modified and saved as {new_filename}") 19 | 20 | except FileNotFoundError: 21 | print("Error: The file does not exist. Please check the filename and try again.") 22 | except PermissionError: 23 | print("Error: Permission denied. You don’t have access to this file.") 24 | except Exception as e: 25 | print(f"An unexpected error occurred: {e}") 26 | 27 | # Run the function 28 | read_and_modify_file() 29 | -------------------------------------------------------------------------------- /weatherApp.py: -------------------------------------------------------------------------------- 1 | wimport requests 2 | import tkinter as tk 3 | from tkinter import messagebox 4 | from PIL import Image, ImageTk 5 | import io 6 | 7 | def get_weather(city): 8 | api_key = 'd6b1377bde26a469fc276ec2dd366e7c' # Replace with your OpenWeatherMap API key 9 | base_url = 'http://api.openweathermap.org/data/2.5/weather' 10 | params = { 11 | 'q': city, 12 | 'appid': api_key, 13 | 'units': 'metric' # Use 'imperial' for Fahrenheit 14 | } 15 | 16 | try: 17 | response = requests.get(base_url, params=params) 18 | response.raise_for_status() # Will raise HTTPError for bad responses 19 | data = response.json() 20 | return data 21 | except requests.exceptions.HTTPError as err: 22 | if response.status_code == 404: 23 | messagebox.showerror("Error", "City not found. Please enter a valid city name.") 24 | else: 25 | messagebox.showerror("Error", f"HTTP Error: {err}") 26 | except requests.exceptions.RequestException as err: 27 | messagebox.showerror("Error", f"Request Error: {err}") 28 | return None 29 | 30 | def display_weather(): 31 | city = city_entry.get() 32 | weather_data = get_weather(city) 33 | 34 | if weather_data: 35 | city_name = weather_data['name'] 36 | temperature = weather_data['main']['temp'] 37 | weather_description = weather_data['weather'][0]['description'] 38 | humidity = weather_data['main']['humidity'] 39 | wind_speed = weather_data['wind']['speed'] 40 | icon_code = weather_data['weather'][0]['icon'] 41 | icon_url = f"http://openweathermap.org/img/wn/{icon_code}.png" 42 | 43 | # Update GUI labels 44 | city_label.config(text=f"City: {city_name}") 45 | temp_label.config(text=f"Temperature: {temperature}°C") 46 | desc_label.config(text=f"Weather: {weather_description.capitalize()}") 47 | humidity_label.config(text=f"Humidity: {humidity}%") 48 | wind_label.config(text=f"Wind Speed: {wind_speed} m/s") 49 | 50 | # Update weather icon 51 | icon_response = requests.get(icon_url) 52 | icon_data = icon_response.content 53 | icon_image = Image.open(io.BytesIO(icon_data)) 54 | icon_photo = ImageTk.PhotoImage(icon_image) 55 | icon_label.config(image=icon_photo) 56 | icon_label.image = icon_photo 57 | else: 58 | city_label.config(text="") 59 | temp_label.config(text="") 60 | desc_label.config(text="") 61 | humidity_label.config(text="") 62 | wind_label.config(text="") 63 | icon_label.config(image="") 64 | 65 | # Setup Tkinter window 66 | root = tk.Tk() 67 | root.title("Weather App") 68 | 69 | # City input 70 | city_entry = tk.Entry(root) 71 | city_entry.pack(pady=10) 72 | 73 | # Get weather button 74 | get_weather_btn = tk.Button(root, text="Get Weather", command=display_weather) 75 | get_weather_btn.pack(pady=5) 76 | 77 | # Weather info labels 78 | city_label = tk.Label(root, text="", font=('bold', 14)) 79 | city_label.pack() 80 | 81 | temp_label = tk.Label(root, text="") 82 | temp_label.pack() 83 | 84 | desc_label = tk.Label(root, text="") 85 | desc_label.pack() 86 | 87 | humidity_label = tk.Label(root, text="") 88 | humidity_label.pack() 89 | 90 | wind_label = tk.Label(root, text="") 91 | wind_label.pack() 92 | 93 | # Weather icon label 94 | icon_label = tk.Label(root, image=None) 95 | icon_label.pack(pady=10) 96 | 97 | root.mainloop() 98 | --------------------------------------------------------------------------------