Overview: To-Do List Manager
Let’s get started with Mutable Default Arguments in Python. In Python, mutable default arguments like list and dictionaries are evaluated once when the function is defined, not each time when the function is called.
Learn how to deal with Mutable Default Arguments in Python and how to fix that problem.
What’s Next? – To-Do List Manager
In this article, let’s explore how to deal with To-Do List Manager in Python. Along with this, you will grab a strong command of how to use the if-else conditional statement inside the def function and also learn about usage of try-except block code in Python.
Table of Contents
def to_do_list():
tasks = []
while True:
print("1. Add Task")
print("2. View Task")
print("3. Delete Task")
print("4. Exit...")
print()
choice = input("Enter the task number (1-4): ")
print()
#user == 1 --> add task
if choice == '1':
task = input("Enter the task: ")
tasks.append(task)
print(f"Task: '{task}' added successfully.")
print()
#user == 2 --> View Task
elif choice == '2':
if not tasks:
print("No task is in the list.")
print()
else:
for index, task in enumerate(tasks, start=1):
print(f"{index}.{task}")
print()
#user == 3 --> Delete Task
elif choice == '3':
if not tasks:
print("No task is in the list.")
print()
else:
for index, task in enumerate(tasks, start=1):
print(f"{index}.{task}")
try:
print()
task_num = int(input("Enter the task number to delete: "))-1
if 0 <= task_num < len(tasks): # user'task number > total number of tasks
remove_task = tasks.pop(task_num)
print(f"Task '{remove_task}' is deleted.")
print()
else:
print("Invalid number")
print()
except ValueError:
print("Invalid number. Try again.")
print()
elif choice == "4":
print("Exit. Goodbye.")
print()
break
else:
print("Invalid choice! Please try again.")
print()
if __name__ == "__main__":
to_do_list()
How Does It Work?
Adding a Task → User enters a task, and it gets stored in a list.
Viewing Tasks → Displays all tasks with numbers.
Deleting a Task → User selects a task by number to remove it.
Exiting → Ends the program.
Explanation:
First of all, I wrote the whole program inside the function, so that we can run the whole program together forever without writing explicitly code for each time for running.
def to_do_list():
tasks = []
1. First, I defined a function named to_do_list() and inside it stored an empty list to add all tasks (to-do items).
while True:
2. Next, I started with a while loop which runs infinite times, until the user chooses to make an exit. In other words, the to-do list manager program will keep asking for an input until the user selects to exit.
print("1. Add Task")
print("2. View Tasks")
print("3. Delete Task")
print("4. Exit")
3. Next, inside the while loop defined the menu options like: add, view, and delete tasks. So, each time the program runs, the user will be asked to choose an option to run the program.
choice = input("Enter your choice (1-4): ")
4. Next, a variable is declared with name choice with Python input() function, which asks the user to enter a number according to given options to run the program.
Now based on the choice:
5. If user picks “1”: Add a Task
task = input("Enter the task: ")
tasks.append(task)
print(f"Task '{task}' added successfully!")
The program asks the user to type a task which will be added to the tasks variable (a list contains all tasks) by using Python list – append method. Next it displays the statement using Python print() function, but here I used string format to add the customized value using placeholder {} into the final statement.
6. If user picks “2”: View Tasks
if not tasks:
print("No tasks in the list!")
else:
for index, task in enumerate(tasks, start=1):
print(f"{index}. {task}")
Next, if the list is empty i.e., no task is added yet, then it displays the statement – “No tasks in the list!”
Otherwise, show all the tasks with the corresponding numbers.
Python enumerate() function is used to add the number to each task. The index variable is used with a for loop to identify the index number of each task and assign it to the enumerate() function.
7. If user picks “3”: Delete a Task
if not tasks:
print("No tasks to delete!")
else:
for index, task in enumerate(tasks, start=1):
print(f"{index}. {task}")
For the above code, the explanation is the same as point 6.
try:
task_num = int(input("Enter task number to delete: ")) - 1
if 0 <= task_num < len(tasks):
removed_task = tasks.pop(task_num)
print(f"Task '{removed_task}' deleted!")
else:
print("Invalid task number!")
except ValueError:
print("Please enter a valid number!")
Next, program asks number from the user to delete the task from the list using .pop(index) method. The user given number is subtracted by -1 because the index number starts from 0.
Next, if the condition checks if the user’s given task number is < total number of tasks, then that task will be deleted from the list else the number is invalid.
Also handles errors using the except block of code
If a user enters the text instead of a number or a number that’s out of range.
If user picks “4”: Exit
elif choice == "4":
print("Exiting... Goodbye!")
break
Next, end the loop and exit the program, when the user selects 4.
Else: Invalid input
else:
print("Invalid choice! Please try again.")
if __name__ == "__main__":
to_do_list()
Finally:
This makes sure the program runs only if it’s executed directly, not if it’s imported somewhere else.
Conclusion: T0-Do List Manager
This is a beginner-friendly project to practice that makes a strong command on Python topics like Lists, Loops, User input, Error handling, Conditional statements. This is one of the common Python beginners projects that coder does. So, open your VS code and write code and make your personal to-do list manager and don’t forget what task is added in your list, let’s see whose task is most interesting.