Okay, let's translate the plan for our simple command-line application into actual Python code. We'll build the application piece by piece, integrating the concepts you've learned throughout this course. For this example, let's create a very basic "To-Do List" application.
Remember the plan we outlined? We need functionality to add tasks, view tasks, mark tasks as complete, and exit. We also decided on a structure to hold our data.
First, create a new Python file. Let's name it todo_app.py
.
Inside this file, we need a way to store our tasks. A list is a good choice, where each item in the list represents a single task. How should we represent a task? A dictionary seems suitable, allowing us to store the task description and its status (e.g., 'pending' or 'complete').
# todo_app.py
# Start with an empty list to hold our tasks.
# Each task will be a dictionary like: {'description': 'Do homework', 'status': 'pending'}
tasks = []
This sets up the foundation. tasks
is currently an empty list, ready to hold our task dictionaries.
Now, let's create functions for each action our application needs to perform. This approach makes our code modular and easier to understand, reflecting the principles from Chapter 5 (Functions).
We need a function that asks the user for a task description and adds it to our tasks
list with a 'pending' status.
def add_task(task_list):
"""Asks the user for a task description and adds it to the list."""
description = input("Enter the task description: ")
new_task = {'description': description, 'status': 'pending'}
task_list.append(new_task)
print(f"Task '{description}' added.")
# Example usage (we'll integrate this into the main loop later)
# add_task(tasks)
# print(tasks)
This function takes the main task_list
as an argument, gets input, creates the dictionary, and uses the append
method (from Chapter 4 on Lists) to add it.
We need a way to display all the tasks, perhaps with a number so the user can easily refer to them. We should also handle the case where there are no tasks yet.
def view_tasks(task_list):
"""Displays all tasks with their index and status."""
print("\n--- Your Tasks ---")
if not task_list:
print("No tasks yet!")
return
# Enumerate provides both index and item, useful here.
for index, task in enumerate(task_list):
# Display index starting from 1 for user-friendliness
print(f"{index + 1}. {task['description']} [{task['status']}]")
print("------------------")
# Example usage:
# view_tasks(tasks) # Initially will show "No tasks yet!"
# add_task(tasks)
# view_tasks(tasks)
This function iterates through the task_list
. It uses enumerate
to get both the index (starting from 0) and the task dictionary. We add 1 to the index for display purposes, making it more natural for users (1, 2, 3...). It checks if the list is empty before trying to loop.
This function needs to show the tasks, ask the user which one to mark complete, validate the input, and update the status in the chosen task dictionary. This involves using concepts from Chapter 3 (Control Flow) and potentially Chapter 9 (Error Handling).
def mark_complete(task_list):
"""Marks a specific task as complete."""
view_tasks(task_list) # Show tasks first so user can choose
if not task_list: # Can't mark complete if list is empty
return
while True: # Loop until valid input is received
try:
task_number_str = input("Enter the number of the task to mark complete: ")
# Convert input string to an integer (Chapter 2)
task_index = int(task_number_str) - 1 # Adjust for 0-based index
# Check if the index is valid (Chapter 3, Conditionals)
if 0 <= task_index < len(task_list):
# Modify the dictionary directly within the list (Chapter 4)
task_list[task_index]['status'] = 'complete'
print(f"Task {task_index + 1} marked as complete.")
break # Exit the input loop
else:
print("Invalid task number. Please try again.")
except ValueError:
# Handle case where input is not a number (Chapter 9)
print("Invalid input. Please enter a number.")
# Example usage:
# add_task(tasks) # Add a task first
# mark_complete(tasks)
# view_tasks(tasks)
Here, we first display the tasks. Then, we ask the user for the number. We use a while True
loop with try-except
(Chapter 9) to handle potential ValueError
if the user enters something that isn't a number. We also check if the number corresponds to a valid index in our list. If the input is valid, we access the specific task dictionary using its index (task_list[task_index]
) and change the value associated with the 'status'
key. We then break
out of the input loop.
Now we need the main part of the application that runs continuously, shows the user a menu of options, gets their choice, and calls the appropriate function. This uses a while
loop and if/elif/else
statements (Chapter 3).
def display_menu():
"""Prints the menu options."""
print("\n--- To-Do List Menu ---")
print("1. Add Task")
print("2. View Tasks")
print("3. Mark Task as Complete")
print("4. Exit")
print("-----------------------")
# --- Main Application Execution ---
if __name__ == "__main__": # Standard practice, explained briefly later
print("Welcome to the Simple To-Do List!")
while True: # Main application loop
display_menu()
choice = input("Enter your choice (1-4): ")
if choice == '1':
add_task(tasks)
elif choice == '2':
view_tasks(tasks)
elif choice == '3':
mark_complete(tasks)
elif choice == '4':
print("Exiting the To-Do List application. Goodbye!")
break # Exit the while loop
else:
print("Invalid choice. Please enter a number between 1 and 4.")
# Optional: Add saving tasks to a file here before exiting
# print("Tasks saved.") # Placeholder
The display_menu
function simply prints the options. The main part runs within a while True
loop. It shows the menu, gets the user's choice
, and uses if/elif/else
to determine which function to call. If the choice is '4', it prints a goodbye message and uses break
to terminate the loop, ending the program. An else
clause handles invalid input.
The if __name__ == "__main__":
line is a common Python construct. It means the code inside this block will only run when the script is executed directly (not when it's imported as a module into another script, which we discussed in Chapter 7). For our simple application, it marks the starting point of execution.
Let's combine all the pieces into the final todo_app.py
file:
# todo_app.py
# Start with an empty list to hold our tasks.
tasks = []
def add_task(task_list):
"""Asks the user for a task description and adds it to the list."""
description = input("Enter the task description: ")
# Basic validation: ensure description is not empty
if description.strip(): # strip() removes leading/trailing whitespace
new_task = {'description': description, 'status': 'pending'}
task_list.append(new_task)
print(f"Task '{description}' added.")
else:
print("Task description cannot be empty.")
def view_tasks(task_list):
"""Displays all tasks with their index and status."""
print("\n--- Your Tasks ---")
if not task_list:
print("No tasks yet!")
return
for index, task in enumerate(task_list):
print(f"{index + 1}. {task['description']} [{task['status']}]")
print("------------------")
def mark_complete(task_list):
"""Marks a specific task as complete."""
view_tasks(task_list)
if not task_list:
return
while True:
try:
task_number_str = input("Enter the number of the task to mark complete (or 0 to cancel): ")
task_number = int(task_number_str)
if task_number == 0: # Allow user to cancel
break
task_index = task_number - 1
if 0 <= task_index < len(task_list):
# Check if already complete to avoid unnecessary updates
if task_list[task_index]['status'] == 'complete':
print(f"Task {task_number} is already marked as complete.")
else:
task_list[task_index]['status'] = 'complete'
print(f"Task {task_number} marked as complete.")
break
else:
print("Invalid task number. Please try again.")
except ValueError:
print("Invalid input. Please enter a number.")
def display_menu():
"""Prints the menu options."""
print("\n--- To-Do List Menu ---")
print("1. Add Task")
print("2. View Tasks")
print("3. Mark Task as Complete")
print("4. Exit")
print("-----------------------")
# --- Main Application Execution ---
if __name__ == "__main__":
print("Welcome to the Simple To-Do List!")
# Future enhancement: Load tasks from a file here
while True:
display_menu()
choice = input("Enter your choice (1-4): ")
if choice == '1':
add_task(tasks)
elif choice == '2':
view_tasks(tasks)
elif choice == '3':
mark_complete(tasks)
elif choice == '4':
# Future enhancement: Save tasks to a file here
print("Exiting the To-Do List application. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
Save this code as todo_app.py
. Open your terminal or command prompt, navigate to the directory where you saved the file, and run it using:
python todo_app.py
You should see the welcome message and the menu. Try adding tasks, viewing them, and marking them complete.
This step-by-step process demonstrates how to build a simple application by:
add_task
, view_tasks
, mark_complete
).while
, if/elif/else
) to manage the application's execution and user interaction.try-except
) for robustness.While basic, this structure forms the basis for many command-line tools and integrates numerous concepts covered in this course. The next section discusses testing this application.
© 2025 ApX Machine Learning