Create a To Do List in Python with Source Code

04 May 2023 Balmiki Mandal 0 Python

Creating a To-Do List in Python with Source Code

Python is one of the most popular programming languages and is used by thousands of developers across the globe. One task that Python is particularly useful for is creating a to-do list. By utilizing for loops, if statements, and other control structures, you can create a program that allows users to store any tasks they have to do in one place. Below, we will cover the source code needed to build a basic to-do list in Python:

# Create an empty list to store tasks
todo_list = [] 

# Add a task in the list
def add_task(task):
    todo_list.append(task)
    print("Task has been added")

# View all tasks in the list
def view_all_tasks():
    count = 1
		for task in todo_list:
			print(str(count) + ": " + task)
			count+=1

# Delete a task from the list
def delete_task(index):
		index -= 1
		del todo_list[index]
		print("Task deleted")

# Main function which runs the program
def main():
		while True:
				print("Select any option")
				print("1. Add task")
				print("2. View all tasks")
				print("3. Delete task")
				print("4. Exit")

				option = int(input())

				if option == 1:
						task = input("Enter task: ")
						add_task(task)

				elif option == 2:
						view_all_tasks()

				elif option == 3:
						index = int(input("Enter index of task to delete: "))
						delete_task(index)

				elif option == 4:
						break

if __name__ == "__main__":
		main()

The above source code displays a menu to the user with four options: 1. Add a task 2. View all tasks 3. Delete a task 4. Exit The user is then able to select one of these items and perform the associated action. The code utilizes various functions to complete each task such as add_task() and view_all_tasks(). It also uses an infinite loop so that it can continuously prompt the user for a command until they decide to exit out of the program. By running the above source code, you can easily build a basic to-do list in Python. This example can be used as the foundation for more complex applications that require features such as task prioritization or recurring tasks.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.