2D Dynamic Lists
Dynamic lists are lists that we populate as we go, getting user input and adding it to the list as we go.We're combining several techniques here. I've left detailed code comments to help. Remember, comments can be found with # comment in green inside the code.
Once we collect the user's input in a row, we will append the entire row to the list. The columns are maintained, and we are keeping the structure of 2D lists.
Lets try this coding :
listOfShame = []
# Creates an empty list.
while True:
# Starts a never ending loop (until we end it)
name = input("What is your name? ")
age = input("What is your age? ")
pref = input("What is your computer platform? ")
# Get the user input.
row = [name, age, pref]
# Assigns the 3 variables into a single row.
listOfShame.append(row)
# Adds the contents of the row variable at the end of the list
exit = input("Exit? y/n")
# Get user choice to quit, yes or no?
if (exit.strip().lower()[0] == "y"):
# strip removes unwanted spaces from the input. lower()[0] makes sure the first character of the input is lower case so it can be compared to 'y'
break # break ends a loop and jumps to the next line of code that is not part of the loop.
print(listOfShame) # Outputs the list. Note this is NOT part of the loop (not indented), it only runs once the loop ends.
Pretty Printing
Man, that print(listOfShame) output sure is ug-leeee.
In the code below, I've added a prettyPrint subroutine to beautify the output.
def prettyPrint():
print()
# Puts a blank row at the top
for row in listOfShame:
#loops to the next row when the end of the current one is reached
print(row)
# prints the new row
print()
# prints a blank line between rows
listOfShame = []
while True:
name = input("What is your name? ")
age = input("What is your age? ")
pref = input("What is your computer platform? ")
row = [name, age, pref]
listOfShame.append(row)
exit = input("Exit? y/n")
if (exit.strip().lower()[0] == "y"):
break
prettyPrint()
# Call the prettyPrint subroutine instead of printing the list directly.
This version of prettyPrint() uses fStrings to further line up the tabs.
Note: this only shows the updated subroutine.
def prettyPrint():
print()
for row in listOfShame:
for item in row:
# item refers to each item in the column for that row
print(f"{item:^10}", end=" | ")
listOfShame = []
while True:
name = input("What is your name? ")
age = input("What is your age? ")
pref = input("What is your computer platform? ")
row = [name, age, pref]
listOfShame.append(row)
exit = input("Exit? y/n")
if (exit.strip().lower()[0] == "y"):
break
prettyPrint()
# Call the prettyPrint subroutine instead of printing the list directly.
We ask the user to choose between adding and removing. If they choose remove, we
-ask for a name on the list (make sure it is spelled correctly)
-extract each row, one at a time, from the list
-check the row to see if it contains the name
-if the name is in the row, use the .remove() method to remove the whole row, not just the name.
Coding Challenge
1. Have a menu that asks if you want to add, view, move or edit a 'to do'.
2.If you choose 'add' then the system should:Prompt you to input what the to do is, when it is due by and the priority (high, medium or low).
Add the 'to do' to the list.
3. 'View' should give two options:View all - shows all 'to dos' with a pretty print.
View priority - allows you to search for high, medium or low priority and only see matching tasks.
4.'Edit' allows you to change any of the information within one of the 'to dos'.
5. 'Remove' lets you completely remove a 'to do' when it is 'to done'.
STEP-1
# Function to add a to do
def add_todo():
task = input("Enter the task: ")
due_date = input("Enter the due date: ")
priority = input("Enter the priority (high, medium, low): ")
todo_list.append({'Task': task, 'Due Date': due_date, 'Priority': priority})
print("Task added successfully.")
# Function to view all todos
def view_all():
print("All To Dos:")
print(f"{index}. Task: {todo['Task']}, Due Date: {todo['Due Date']}, Priority: {todo['Priority']}")
# Function to view todos by priority
def view_priority(priority):
print(f"To Dos with priority {priority}:")
for index, todo in enumerate(todo_list, start=1):
if todo['Priority'].lower() == priority.lower():
print(f"{index}. Task: {todo['Task']}, Due Date: {todo['Due Date']}, Priority: {todo['Priority']}")
# Function to edit a todo
def edit_todo():
view_all()
index = int(input("Enter the index of the task you want to edit: ")) - 1
if 0 <= index < len(todo_list):
task = input("Enter the new task: ")
due_date = input("Enter the new due date: ")
priority = input("Enter the new priority (high, medium, low): ")
todo_list[index] = {'Task': task, 'Due Date': due_date, 'Priority': priority}
print("Task edited successfully.")
else:
print("Invalid index.")
# Function to remove a todo
def remove_todo():
view_all()
index = int(input("Enter the index of the task you want to remove: ")) - 1
if 0 <= index < len(todo_list):
del todo_list[index]
print("Task removed successfully.")
else:
print("Invalid index.")
# Main program
todo_list = []
while True:
print("\nMenu:")
print("1. Add a To Do")
print("2. View To Dos")
print("3. Edit a To Do")
print("4. Remove a To Do")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_todo()
elif choice == '2':
print("\nView Options:")
print("1. View All")
print("2. View by Priority")
view_choice = input("Enter your choice: ")
if view_choice == '1':
view_all()
elif view_choice == '2':
priority = input("Enter the priority (high, medium, low): ")
view_priority(priority)
else:
print("Invalid choice.")
elif choice == '3':
edit_todo()
elif choice == '4':
remove_todo()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number from 1 to 5.")
-extract each row, one at a time, from the list
-check the row to see if it contains the name
-if the name is in the row, use the .remove() method to remove the whole row, not just the name.
def prettyPrint():
print()
for row in listOfShame:
for item in row:
# item refers to each item in the column for that row
print(f"{item:^10}", end=" | ")
listOfShame = []
while True:
menu = input("Add or Remove?") # Gives the user a choice prompt and stores their input.
if(menu.strip().lower()[0]=="a"): # Uses selection to run the 'add' code if user inputs 'a'. I've "sanitized" the input here too.[0]: This indexing operation accesses the first character of the modified string obtained after stripping whitespace and converting to lowercase. Indexing in Python starts from 0, so [0] accesses the first character of the string.
name = input("What is your name? ")
age = input("What is your age? ")
pref = input("What is your computer platform? ")
row = [name, age, pref]
listOfShame.append(row)
# All the 'add' code is now indented, so it's part of the 'add' branch and will only run if the user enters 'a'.
else: # If the user doesn't choose 'a', run this new remove code instead.
name = input("What is the name of the record to delete?") # Get the input of a name
for row in listOfShame: # Use a loop to extract one row at a time
if name in row: # Check if the name is in the extracted row.
listOfShame.remove(row) # remove the whole row if name is in it
prettyPrint()
1. Have a menu that asks if you want to add, view, move or edit a 'to do'.
2.If you choose 'add' then the system should:Prompt you to input what the to do is, when it is due by and the priority (high, medium or low).
Add the 'to do' to the list.
3. 'View' should give two options:View all - shows all 'to dos' with a pretty print.
View priority - allows you to search for high, medium or low priority and only see matching tasks.
4.'Edit' allows you to change any of the information within one of the 'to dos'.
5. 'Remove' lets you completely remove a 'to do' when it is 'to done'.
STEP-1
def add_todo():
task = input("Enter the task: ")
due_date = input("Enter the due date: ")
priority = input("Enter the priority (high, medium, low): ")
todo_list.append({'Task': task, 'Due Date': due_date, 'Priority': priority})
print("Task added successfully.")
# Function to view all todos
def view_all():
print("All To Dos:")
print(f"{index}. Task: {todo['Task']}, Due Date: {todo['Due Date']}, Priority: {todo['Priority']}")
# Function to view todos by priority
def view_priority(priority):
print(f"To Dos with priority {priority}:")
for index, todo in enumerate(todo_list, start=1):
if todo['Priority'].lower() == priority.lower():
print(f"{index}. Task: {todo['Task']}, Due Date: {todo['Due Date']}, Priority: {todo['Priority']}")
# Function to edit a todo
def edit_todo():
view_all()
index = int(input("Enter the index of the task you want to edit: ")) - 1
if 0 <= index < len(todo_list):
task = input("Enter the new task: ")
due_date = input("Enter the new due date: ")
priority = input("Enter the new priority (high, medium, low): ")
todo_list[index] = {'Task': task, 'Due Date': due_date, 'Priority': priority}
print("Task edited successfully.")
else:
print("Invalid index.")
# Function to remove a todo
def remove_todo():
view_all()
index = int(input("Enter the index of the task you want to remove: ")) - 1
if 0 <= index < len(todo_list):
del todo_list[index]
print("Task removed successfully.")
else:
print("Invalid index.")
# Main program
todo_list = []
while True:
print("\nMenu:")
print("1. Add a To Do")
print("2. View To Dos")
print("3. Edit a To Do")
print("4. Remove a To Do")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_todo()
elif choice == '2':
print("\nView Options:")
print("1. View All")
print("2. View by Priority")
view_choice = input("Enter your choice: ")
if view_choice == '1':
view_all()
elif view_choice == '2':
priority = input("Enter the priority (high, medium, low): ")
view_priority(priority)
else:
print("Invalid choice.")
elif choice == '3':
edit_todo()
elif choice == '4':
remove_todo()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number from 1 to 5.")
STEP-2
# | Name | Date | Priority
import os, time
todo = []
def add():
time.sleep(1)
os.system("clear")
name = input("Name > ")
date = input("Due Date > ")
priority = input("Priority > ").capitalize()
row = [name, date, priority]
todo.append(row)
print("Added")
def view():
time.sleep(1)
os.system("clear")
options = input("1: All\n2: By Priority\n> ")
if options=="1":
for row in todo:
for item in row:
print(item, end=" | ")
print()
print()
else:
priority = input("What priority? > ").capitalize()
for row in todo:
if priority in row:
for item in row:
print(item, end=" | ")
print()
print()
time.sleep(1)
def edit():
time.sleep(1)
os.system("clear")
find = input("Name of todo to edit > ")
found = False
for row in todo:
if find in row:
found = True
if not found:
print("Couldn't find that")
return
for row in todo:
if find in row:
todo.remove(row)
name = input("Name > ")
date = input("Due Date > ")
priority = input("Priority > ").capitalize()
row = [name, date, priority]
todo.append(row)
print("Added")
def remove():
time.sleep(1)
os.system("clear")
find = input("Name of todo to remove > ")
for row in todo:
if find in row:
todo.remove(row)
while True:
menu = input("1: Add\n2: View\n3: Edit\n4: Remove\n> ")
if menu == "1":
add()
elif menu == "2":
view()
elif menu == "3":
edit()
else:
remove()
time.sleep(1)
os.system("clear")