01

Working with Files (Basic)

Reading from a Text File

Reading Files
# Reading entire file
with open("example.txt", "r") as file:
    content = file.read()
    print("File content:")
    print(content)

# Reading line by line
with open("example.txt", "r") as file:
    print("\nReading line by line:")
    for line in file:
        print(line.strip())  # strip() removes newline characters

# Reading all lines into a list
with open("example.txt", "r") as file:
    lines = file.readlines()
    print("\nAll lines:")
    for i, line in enumerate(lines, 1):
        print(f"Line {i}: {line.strip()}")

Writing to a Text File

Writing Files
# Writing to a file (overwrites existing content)
with open("output.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a new file.\n")
    file.write("Python is great!")

print("File written successfully!")

# Appending to a file
with open("output.txt", "a") as file:
    file.write("\nThis line was appended.")
    file.write("\nMore content added.")

print("Content appended successfully!")

# Writing multiple lines
lines_to_write = [
    "Line 1",
    "Line 2",
    "Line 3"
]

with open("output.txt", "w") as file:
    file.writelines("\n".join(lines_to_write))

print("Multiple lines written!")

Simple File-Based Programs

Contact Manager (Simple)
# Simple contact manager
def add_contact(name, phone, filename="contacts.txt"):
    """Add a contact to the file"""
    with open(filename, "a") as file:
        file.write(f"{name},{phone}\n")
    print(f"Contact {name} added successfully!")

def view_contacts(filename="contacts.txt"):
    """View all contacts"""
    try:
        with open(filename, "r") as file:
            print("\nContacts:")
            print("-" * 30)
            for line in file:
                name, phone = line.strip().split(",")
                print(f"Name: {name}, Phone: {phone}")
    except FileNotFoundError:
        print("No contacts found. File doesn't exist yet.")

# Usage
add_contact("Alice", "123-456-7890")
add_contact("Bob", "987-654-3210")
view_contacts()
02

Introduction to GitHub (Light & Practical)

What is GitHub?

GitHub is a web-based platform that uses Git for version control. It's like a social network for code where developers can store, share, and collaborate on projects.

Why Developers Use GitHub

📦 Version Control

Track changes to your code over time

💾 Backup

Store your code in the cloud

👥 Collaboration

Work with others on the same project

💼 Portfolio

Showcase your work to potential employers

🌐 Open Source

Contribute to and learn from public projects

Git vs GitHub (Simple Explanation)

  • Git: A version control system (tool) that runs on your computer
  • GitHub: A website/service that hosts Git repositories online
  • Think of Git as the engine and GitHub as the car - Git does the work, GitHub provides the platform
03

GitHub Hands-On

Creating a GitHub Account

  1. Visit github.com
  2. Click "Sign up"
  3. Enter your email, password, and username
  4. Verify your email address
  5. Complete the setup process

Creating a Repository

  1. Click the "+" icon in the top right corner
  2. Select "New repository"
  3. Enter a repository name (e.g., "python-course-projects")
  4. Add a description (optional)
  5. Choose public or private
  6. Click "Create repository"

Uploading Python Files

Using GitHub Desktop (Recommended for Beginners):

  1. Download and install GitHub Desktop
  2. Sign in with your GitHub account
  3. Click "File" → "Add Local Repository"
  4. Select your project folder
  5. Click "Publish repository" to upload to GitHub

Using Web Interface:

  1. Go to your repository on GitHub
  2. Click "uploading an existing file"
  3. Drag and drop your Python files
  4. Enter a commit message (e.g., "Add Python practice files")
  5. Click "Commit changes"

Making Simple Commits

A commit is like saving a snapshot of your code at a specific point in time.

  • Commit Message: A brief description of what changes you made
  • Examples: "Add hello world program", "Fix bug in calculator", "Update README"

Viewing Code History

  1. Go to your repository on GitHub
  2. Click on a file
  3. Click "History" to see all previous versions
  4. You can see who made changes and when
04

Mini Project

Create a small Python project using all the concepts you've learned!

Project Options:

Option 1: Simple Contact Manager

Complete Contact Manager Program
# Contact Manager - Mini Project
FILENAME = "contacts.txt"

def display_menu():
    """Display the main menu"""
    print("\n" + "="*40)
    print("CONTACT MANAGER")
    print("="*40)
    print("1. Add Contact")
    print("2. View All Contacts")
    print("3. Search Contact")
    print("4. Delete Contact")
    print("5. Exit")
    print("="*40)

def add_contact():
    """Add a new contact"""
    name = input("Enter name: ")
    phone = input("Enter phone number: ")
    
    with open(FILENAME, "a") as file:
        file.write(f"{name},{phone}\n")
    print(f"\nContact '{name}' added successfully!")

def view_contacts():
    """View all contacts"""
    try:
        with open(FILENAME, "r") as file:
            contacts = file.readlines()
            
            if not contacts:
                print("\nNo contacts found!")
                return
            
            print("\n" + "-"*40)
            print("ALL CONTACTS")
            print("-"*40)
            for i, line in enumerate(contacts, 1):
                name, phone = line.strip().split(",")
                print(f"{i}. Name: {name}, Phone: {phone}")
            print("-"*40)
    except FileNotFoundError:
        print("\nNo contacts found! File doesn't exist yet.")

def search_contact():
    """Search for a contact"""
    search_name = input("Enter name to search: ")
    
    try:
        with open(FILENAME, "r") as file:
            found = False
            for line in file:
                name, phone = line.strip().split(",")
                if search_name.lower() in name.lower():
                    print(f"\nFound: Name: {name}, Phone: {phone}")
                    found = True
            
            if not found:
                print(f"\nContact '{search_name}' not found!")
    except FileNotFoundError:
        print("\nNo contacts found! File doesn't exist yet.")

def delete_contact():
    """Delete a contact"""
    delete_name = input("Enter name to delete: ")
    
    try:
        with open(FILENAME, "r") as file:
            contacts = file.readlines()
        
        new_contacts = []
        deleted = False
        
        for line in contacts:
            name, phone = line.strip().split(",")
            if name.lower() != delete_name.lower():
                new_contacts.append(line)
            else:
                deleted = True
        
        if deleted:
            with open(FILENAME, "w") as file:
                file.writelines(new_contacts)
            print(f"\nContact '{delete_name}' deleted successfully!")
        else:
            print(f"\nContact '{delete_name}' not found!")
    except FileNotFoundError:
        print("\nNo contacts found! File doesn't exist yet.")

# Main program loop
def main():
    """Main program function"""
    while True:
        display_menu()
        choice = input("\nEnter your choice (1-5): ")
        
        if choice == "1":
            add_contact()
        elif choice == "2":
            view_contacts()
        elif choice == "3":
            search_contact()
        elif choice == "4":
            delete_contact()
        elif choice == "5":
            print("\nThank you for using Contact Manager!")
            break
        else:
            print("\nInvalid choice! Please try again.")

# Run the program
if __name__ == "__main__":
    main()

Option 2: To-Do List

Complete To-Do List Program
# To-Do List - Mini Project
FILENAME = "todo.txt"

def display_menu():
    """Display the main menu"""
    print("\n" + "="*40)
    print("TO-DO LIST MANAGER")
    print("="*40)
    print("1. Add Task")
    print("2. View Tasks")
    print("3. Mark Task as Complete")
    print("4. Delete Task")
    print("5. Exit")
    print("="*40)

def add_task():
    """Add a new task"""
    task = input("Enter task: ")
    
    with open(FILENAME, "a") as file:
        file.write(f"{task},False\n")  # False means not completed
    print(f"\nTask '{task}' added successfully!")

def view_tasks():
    """View all tasks"""
    try:
        with open(FILENAME, "r") as file:
            tasks = file.readlines()
            
            if not tasks:
                print("\nNo tasks found!")
                return
            
            print("\n" + "-"*40)
            print("YOUR TASKS")
            print("-"*40)
            for i, line in enumerate(tasks, 1):
                task, completed = line.strip().split(",")
                status = "✓" if completed == "True" else "○"
                print(f"{i}. [{status}] {task}")
            print("-"*40)
    except FileNotFoundError:
        print("\nNo tasks found! File doesn't exist yet.")

def mark_complete():
    """Mark a task as complete"""
    view_tasks()
    try:
        task_num = int(input("\nEnter task number to mark as complete: "))
        
        with open(FILENAME, "r") as file:
            tasks = file.readlines()
        
        if 1 <= task_num <= len(tasks):
            new_tasks = []
            for i, line in enumerate(tasks, 1):
                task, completed = line.strip().split(",")
                if i == task_num:
                    new_tasks.append(f"{task},True\n")
                else:
                    new_tasks.append(line)
            
            with open(FILENAME, "w") as file:
                file.writelines(new_tasks)
            print("\nTask marked as complete!")
        else:
            print("\nInvalid task number!")
    except (ValueError, FileNotFoundError):
        print("\nInvalid input or file not found!")

def delete_task():
    """Delete a task"""
    view_tasks()
    try:
        task_num = int(input("\nEnter task number to delete: "))
        
        with open(FILENAME, "r") as file:
            tasks = file.readlines()
        
        if 1 <= task_num <= len(tasks):
            new_tasks = [task for i, task in enumerate(tasks, 1) if i != task_num]
            
            with open(FILENAME, "w") as file:
                file.writelines(new_tasks)
            print("\nTask deleted successfully!")
        else:
            print("\nInvalid task number!")
    except (ValueError, FileNotFoundError):
        print("\nInvalid input or file not found!")

def main():
    """Main program function"""
    while True:
        display_menu()
        choice = input("\nEnter your choice (1-5): ")
        
        if choice == "1":
            add_task()
        elif choice == "2":
            view_tasks()
        elif choice == "3":
            mark_complete()
        elif choice == "4":
            delete_task()
        elif choice == "5":
            print("\nThank you for using To-Do List Manager!")
            break
        else:
            print("\nInvalid choice! Please try again.")

if __name__ == "__main__":
    main()

Option 3: File-Based Calculator

Complete Calculator Program
# File-Based Calculator - Mini Project
HISTORY_FILE = "calculator_history.txt"

def add(a, b):
    """Add two numbers"""
    return a + b

def subtract(a, b):
    """Subtract two numbers"""
    return a - b

def multiply(a, b):
    """Multiply two numbers"""
    return a * b

def divide(a, b):
    """Divide two numbers"""
    if b == 0:
        return "Error: Division by zero!"
    return a / b

def save_calculation(operation, num1, num2, result):
    """Save calculation to file"""
    with open(HISTORY_FILE, "a") as file:
        file.write(f"{num1} {operation} {num2} = {result}\n")

def view_history():
    """View calculation history"""
    try:
        with open(HISTORY_FILE, "r") as file:
            history = file.readlines()
            
            if not history:
                print("\nNo calculation history found!")
                return
            
            print("\n" + "-"*40)
            print("CALCULATION HISTORY")
            print("-"*40)
            for i, calc in enumerate(history[-10:], 1):  # Show last 10
                print(f"{i}. {calc.strip()}")
            print("-"*40)
    except FileNotFoundError:
        print("\nNo calculation history found!")

def calculator():
    """Main calculator function"""
    print("\n" + "="*40)
    print("CALCULATOR")
    print("="*40)
    print("Operations: +, -, *, /")
    print("Type 'history' to view past calculations")
    print("Type 'quit' to exit")
    print("="*40)
    
    while True:
        try:
            user_input = input("\nEnter calculation (e.g., 5 + 3) or 'quit': ")
            
            if user_input.lower() == "quit":
                print("\nThank you for using Calculator!")
                break
            elif user_input.lower() == "history":
                view_history()
                continue
            
            # Parse input
            parts = user_input.split()
            if len(parts) != 3:
                print("Invalid format! Use: number operator number")
                continue
            
            num1 = float(parts[0])
            operator = parts[1]
            num2 = float(parts[2])
            
            # Perform calculation
            if operator == "+":
                result = add(num1, num2)
            elif operator == "-":
                result = subtract(num1, num2)
            elif operator == "*":
                result = multiply(num1, num2)
            elif operator == "/":
                result = divide(num1, num2)
            else:
                print("Invalid operator! Use +, -, *, or /")
                continue
            
            # Display and save result
            print(f"\nResult: {result}")
            save_calculation(operator, num1, num2, result)
            
        except ValueError:
            print("Invalid input! Please enter numbers.")
        except Exception as e:
            print(f"An error occurred: {e}")

if __name__ == "__main__":
    calculator()