Learn Python by Coding a Simple To-Do List in Python from Scratch
Introduction
What We Want Our To do List to do
Defining the Problem :
Creating a storage space for storing the to do list grocery items that I want to shop. I want to make the list with a menu that shows a menu of choice with features such as Add, View, Edit, Remove, Delete and Exit options. So, I need a way to add items, view them, edit them, remove any of the items if required, delete the entire list if I want and exit the program when I want.
Breaking down the complex steps into mini actions or steps:
A). Adding a New Item to the list
1). Ask what item do you want to add ?
2). I can type the item name into the input box provided
3). The user can click the “Add” option
4). Take the u ser’s text in the input and append that to the end of the item list.
5). The program should be able to mention to the user that the item has been added successfully.
B). Viewing the Items in the list:
1). The program needs to check if the list is empty- if it is, say to the user, “Your list is empty!”
2). If the list is not empty, I need to ensure that the program will go through every item one by one and print out its name.
C). Removing an Item from the list:
1). Show the current list to the user so that he knows the items added in the list.
2). Ask the user what item needs to be removed
3). Check if that item actually exists inside the list
4). Remove the specified item from the list.
D). Updating/Editing an Item in the list:
1). Ask the user what item needs to be updated or edited
2). Ask the user the value of the updated item after editing the current item.
3). Store the value of the updated item in a separate variable
4). The program needs to go through all the items in the list one by one to look for the item to be edited
5). The user inputs the updated value to the program
6). The program will match the previous item with the edited version and replace the specified item with the edited item.
E). Deleting the entire list:
1). Think of a way that the entire is emptied out and cleared of all the data present in the list. In other words, the entire list is reset to an empty list.
F). Ending the program
1). Provide a condition for the infinite program to stop from running infinitely so that the user can stop the program from executing further tasks.
2). Inform the user that the program is going to stop executing any task by printing some message.
# Your Python code goes here
import os, time
toDoList = []
def printList():
print()
for items in toDoList:
print(items)
print()
while True:
menu = input("Do you want to view, add, edit, remove, delete or exit the todo list?\n").lower()
if menu == "view":
printList()
elif menu == "add":
item = input("What do you want to add?\n").title()
toDoList.append(item)
elif menu == "remove":
item = input("What do you want to remove?\n").title()
check = input("Are you sure you want to remove this?\n").lower()
if check.startswith("y"):
if item in toDoList:
toDoList.remove(item)
elif menu == "edit":
item = input("What do you want to edit?\n").title()
new = input("What do you want to change it to?\n").title()
for i in range(0, len(toDoList)):
if toDoList[i] == item:
toDoList[i] = new
elif menu == "delete":
toDoList = []
elif menu == "exit":
break # This breaks the loop and allows the program to reach END
time.sleep(1)
os.system('clear')
What is this about import?
By ‘import’ in python, we bring “add-on packs’ or ‘toolboxes’ into our Python code file. Unless and until we bring or import these toolboxes or packs, Python is not able to talk to the computer or the terminal !
time.sleep(1) —————> The Pause Button
The toolbox: import time
What does it do?
It says to Python : “ You better pause now and do absolutely nothing for a set number of seconds specified ! ( in this case, it is 1 second that is specified)
Why do we need it?
Computers are too fast! If we don’t pause, the program will instantly clear the text before the user even has a chance to read what they just did. It creates a better pace for the user experience.
os.system(“clear”) ———————→ The Eraser
The Toolbox : import os ( OS stands for Operating System like Windows, Mac or Linux).
What does it do?
It communicates directly to the computer’s terminal and runs the command to wipe off the screen squeeky clean! ( Note: for windows, you can use ‘cls’ instead of ‘clear’ ).
Why do we even need it?
It keeps the code workspace clean as otherwise, the terminal will get cluttered easily with too many scrolling history of old menus every time the user enters the options.
Visualizing the Workflow
rough idea about this timeline of events:
User chooses an action
│
▼
[ Action happens: e.g., Item is added ]
│
▼
──► time.sleep(1) ──► Python freezes for 1 second so the user can read the screen.
│
▼
──► os.system(’clear’) ──► The screen is wiped completely blank.
│
▼
[ Loop repeats, showing a clean “ToDo List ” menu at the top ]
so you learn how to create a functional app to interact with in real and you learn how programs interact with the computer
Import tool boxes
As shown below we use the import keyword as this keyword in Python serves to bring in the add-on packs into the code file to serve the purpose of talking to the compter's operating system for handling time-based commands and their execution is clearly explained at the end of the explanation for the entire source code below. The visuals and explanation for the reason of importing the tools os and time have been explained above with a visual diagram.
import os, time
Creating a container to store the items
toDoList = []
We create an empty container , which is a variable in this case called toDoList and to show that it is an empty list, we represent it with a Square bracket without any values inside it.
Next as mentioned in the pseudocode, we need to carry out tasks of adding, viewing, deleting, removing, editing items in the list and for this we need to have a function for this purpose. So we create a function which we define with the def keyword and give it a name of printList() and please note, we can give it any name, you can also call it as def todoList() etc etc.
Create a Custom Display Function
def printList():
print()
for items in toDoList:
print(items)
print()
To show the user what is currently in their list, we have created a custom function called printList(). You can consider it like a function that is more like a saved formula or template that we define it once and re-use it any time we need it later just by calling its name.
print() we used it at the top and bottom:
These are our ‘visual spacers’ and they just print empty lines so that our list could look clean and organized in the terminal and not cluttered or messy.
print(items)
As the python code looks through the list, this command will print each and every individual item on the screen.
while True:
menu = input("Do you want to view, add, edit, remove, delete or exit the todo list?\n").lower()
The above loop is created and yes, it is definitely an infinite loop since we are writing it as while True and you can say that we have just created an intentional infinite loop! The loop condition is the word ‘True” and as we all know from logic that the word “True” is always true, obviously the loop will never stop on its own.
Handling the Menu Options
The Menu options are when the user enters an option to ‘view’, ‘add’, ‘edit’, ‘remove’ or ‘delete’ and so what happens is that the Python program will execute the specific task based on the option presented, and after going through the cycle of options will reach the bottom of the loop and then automatically goes back to the top of the loop to ask the same questions all over again!
This signifies that the program does not bother if the user is viewing, adding, editing, removing or deleting items from the list, rather it will just keep on looping and asking the user the same optional questions on and on .
So, how to stop this loop now?
The only way to stop this loop is when the user will enter the keyword ‘exit’, and this will trigger a ‘break’ command to break the loop and end the program! You will notice that the break statement is associated with the exit option.
if menu == "view":
printList()
Handling the “View” Option
When the user enters his choice, the Python progam uses the conditional statements if and elif to plan what to do next . Take a look at the very first option:
if menu == ‘view’: This step will check if the user entered the option of ‘view’
print(list) If the user did enter the above option, then Python program will trigger the custom function that we created earlier in the program. It will immediately jump to that code, and look at each and every item currently present in the toDoList() at that specific moment and then print out the items clearly on the console screen. Once it is done printing all the items on the screen, it will jump back to the main menu loop to continue the menu loop.
Handling the "Add' Option
elif menu == "add":
item = input("What do you want to add?\n").title()
toDoList.append(item)
Let’s consider the second option of adding new items to the list: If the user enters the option of ‘add’ into the menu, then, the program will prompt the user to input the item name into the add menu and once the user types in the item name, the program will check if it matches with the choice of ‘add’ in the menu options and then on finding a match, it will use the append method to add every new item added by the user , to the end of the list. After performing this task, the program will continue the loop to wait for the user’s next option.
Handling the loop conditions
elif is the shortened form used commonly in Python for ‘else if’ and so it means that if the user did not opt for viewing the list items, then, the program will check if they typed ‘add’ instead and if they did type ‘add’, then, it unlocks the code inside this block or rather activates the code inside this block.
Handling the user input prompt
item = input(" some statement used as a prompt").title()By writing this code, the python program is prompting the user to enter the name of the item or task that they want to add into the list. The title() is used here to automatically capaitalize the first letter of the word that the user enters. Why use the term title? Because, title headings means, every first letter of every word starts with a capital letter, right? For example: if my list needs an item by the name of goat milk, it would read as Goat Milk after I use the title() method above. It is optional and not necessary for beginners to do this project to use title() for naming the items.
Handling the task of appending the items
The append() method in Python is a built-in method that accepts specific text that is entered by the user in this case, as an item variable and adds it directly into the end of our toDoList, rather than just add anything in a random fashion. So every time, the user enters an item, it would be added to the very end of the list that is existing currently. for example, if you consider a list of fruits, that is, fruits = [‘apple’,’cherry’,’orange’] and if a user enters a new item, ‘grapes’, it will be appended to the end of this list and the new list will be fruits = [‘apple’, ‘cherry’, ‘orange’, ‘grapes’]
So, ‘grapes’ was appended or added to the end of the list as shown.
The program will keep accepting and appending the items and once reaches the end of this option, it will automatically loop back to the main menu, eagerly waiting for the user to enter the next option and this will continue until the loop is terminated.
Handling the ‘remove’ option
elif menu == "remove":
item = input("What do you want to remove?\n").title()
check = input("Are you sure you want to remove this?\n").lower()
if check.startswith("y"):
if item in toDoList:
toDoList.remove(item)
Here also we use the loop if-elif-else that continues for all the options for the user to decide what option to select. If the user select the option of ‘remove’, then the program will promoto the user to enter the specific item that is required to be removed and we created the variable, check, to ask if the user is sure that he wants to remove the specified item and if the user answers in confirmation with a 'y' or 'yes', then the program will first check if the specified item is in the list and if it is there in the list, then, the item will be removed from the list. For doing this check, we created the variable check and assigns the value of the input () method to check if the item is sure to be removed by the user or not and after this prompt we use the nested if else condition to say to the program that if the item to be removed is existing inside in the toDoList, then, remove the item from the list.
Managing the Edit Option
elif menu == "edit":
item = input("What do you want to edit?\n").title()
new = input("What do you want to change it to?\n").title()
for i in range(0, len(toDoList)):
if toDoList[i] == item:
toDoList[i] = new
The next condition from the main task of options is to edit the item and when the user selects this option, we create the variable item, to prompt the user to ask what specific item does he want to edit. and another variable, new, to prompt the user to ask what is the value to replace the existing item, meaning the value of the updated item. Then we create the for loop for searching the item and replacing it with a new item and for this we create the range function, where the program tells Python to look at the index positions of the items in the list. There are two parameters inside this range(), one is the number 0, and the second parameter is the len(toDoList). What do you mean by len(toDoList)? This means the total length of the items in the list, or in other words, the total number of items currently inside the list. If there are 10 items inside the list, then, the length of the list is 10. So, by using the above two parameters, what happens is that the program creates a sequence of numbers starting from 0 to the total length, but excluding the total length. Now, what does this mean? If you have a range function from 0 to 7, that means it will look at the items from 0 ( which is the first item as 0 index is for the first item following the index rule) and go on upto 7 , which is the total length of the list at that moment but not 7, ), so in this example, it will yield result of 0,1,2,3,4,5,6 . ( so it will not include the last item with index 7, which is also the total length of the list for this example) Always remember that the last number bears the index number equal to the length of the list as shown in this example.
We use the variable, i as a counter for this loop and every time this loop runs, i acts as the next number in the loop. For example ( 0, next 1, next 2, next 3, nexr 4, next 5, next 6).
Check for the Matched item
if toDoList == item :
This indicates that the program is asked to look at the items with specified index positions inside the counter i . Based on the index positions, the counter will check the item with index 0, which is the first item, then the next with index position 1, which is the second item and so on,
The == or double equal to symbol stands for the exact item or sample. In this code, this means, the counter is asking while checking the matched item, if the item in this counter is exactly the one that the user wants to edit or not?
Swapping for the new item
Look at the code toDoList[i] = new
Note that for python, the index number is shown as i within the square bracket. When the program finds a matched item in the index position, for the item that is to be replaced, it will write the above code . Using the single = sign which is the assignment operator in Python, it will ask the program to bypass or overwrite the current item inside the counter i that has been found to be the one that has to be edited and replaced, and replace it with the new item provided by the user. Remember, we created a variable, new for this purpose, earlier in the program.
Let's understand further by using an example for our grocery to do list.
Presume that our existing toDoList is having following items in the list ['Eggs', 'Bread', 'Yoghurt', 'Milk']
If the user wants to update the item 'Bread' to 'Wheat Bread' so the new item is going to be 'Wheat Bread.
Now the the range function will loop through the items for different index positions or i values in order to follow the above process as explained .
The first time it loops through the items, the index value will be 0 or i=0, whereby the program checks the index position 0, that is doDoList[0] which is actually the first item in the list, that is, 'Eggs' Then it checks, whether the value of 'Eggs' equals 'Bread'. Obviously, the answer is No,so the loop moves on to the second looping process.
In the second loop, it checks the next position, which is toDoList[1] which is the second item in the list, that is, 'Bread'. Now is the value of 'Bread' equal to that of 'Bread' ? Ofcourse, it is a definite 'Yes' and so the program found the match or rather the item to be updated. Since the counter already found the match in the second loop, the program will not run the third or fourth loop.
Execution: The program will change the second item to the value, 'Wheat Bread'. In other words, the program has allocated the value of toDoList[1] = 'Wheat Bread' and then 'Bread' is immediately deleted from the counter and replaced by the updated value of 'Wheat Bread'.
So, the new updated list will be ['Eggs', 'Wheat Bread', 'Yoghurt', 'Milk']
Handling the 'delete' option
Let's consider the code for this execution:
elif menu == "delete":
toDoList = []
Here in the scenario that the user chooses the option of 'delete' , the program will delete all the items from the list and result in an empty list as shown above, toDoList - []
Handling the 'exit' option
Let's consider the code for this execution
elif menu == "exit":
break # This breaks the loop and allows the program to reach END
If the user selects the option of 'exit' then the program will trigger the break command.
Now what break command does is that it immediately terminate the program from the infinite while True loop that we created at the beginning of the program.
The program has reached the End of execution and exits the program even bypassing the last two lines of code below the break statement, that is time.sleep(1) and os.system('clear') because the break command will immediately exit the program even before looking at the below two lines of code and I will just explain below the task of those two lines of tiny code.
Handling the Pausing and Clearing of Screen
time.sleep(1)
os.system('clear')
These two lines of code helps in cleaning up the screen , hence written in the very bottom of the program in the while True loop.
What does time.sleep(1) do
This works as the Pause button. I have myself seen while adding items to the list, updating items in the list etc, the program executes the task so fast , in fact, to the fraction of a millisecond, so much so that I could not even figure out what is printed out in the output screen or see the updated list in the output display screen, so, it creates a confusion in my mind. When I say, this , consider me like a programmer or a user .Obviously, it is very frustrating to the user when he or she cannot see the final output being displayed every time something is being updated or added or removed in the list.
So, In order to avoid this situation, the python program uses the pause button, which is indicated by time.sleep that forces the computer to pause for a specified number of seconds. When it says time.sleep(1) it pauses for 1 second, if you want it to be slower or rather pause for a longer time, you could write, time.sleep(2) or even more. Now, we as a user can comfortably read all the output being displayed at every step of execution of the program.
Lets take a look at os.system('clear')
This works as an clean up system for the program. Immediately after the 1 or 2 second pause, this code will wipe out or rather clear out the terminal screen completely so we have a neat and clean ahead of us!
So, we don't have a history of clogged old output results that will create confusion when we start some other program on a different occasion with all the results of different program cluttering inside the terminal, This is just like having a cluttered wardrobe when you want to find a nice evening dress to go out on a certain day, but, cannot find the dress that you had it all the time, due to the heavy clutter creating a visual confusion and disorder inside your wardrobe!
Conclusion
So the program has a normal while True loop and an exit loop
After executing all the regular tasks of add, view, edit, remove , or delete, the program will reach the bottom of the loop, then pauses for a second and then it clears the screen so that the second time the program runs again from start, you have a clean menu waiting for you at the top of the program.
The moment the user enters the choice of exit, the program will reach the break of the program and runs out of the loop or rather escapes out of the loop, even ignoring the clean up part of the loop, as it's priority is to terminate the program, the moment, the user wants to walk out of the program or end the program.
So, now, you know how the overall loop works in tandem with the exit method as well as the clean up method .
We completed our to dolist in Python and the complete logical explanation of the program is in this post where we deep-dived into the logical building of the simple to do list in Python for complete beginners.

Comments
Post a Comment