#πŸ”’ need help cleaning my todo list terminal app code

21 messages Β· Page 1 of 1 (latest)

pale zenith
#

code:

import time

tasks = []

def view_tasks():
    count = 0
    for task in tasks:
        count += 1
        print(f"#{int(count)} {task}")
        
    if not tasks:
        print("There are currently no tasks.")
        
    print("---------------------")
    main()

def add_tasks():
    task_add = input("Enter the name of your task: ").strip().lower()
    tasks.append(task_add)
    print(f"Task '{task_add}' has successfully been added to the tasks list.")
    
    print("---------------------")
    main()
    
    
    

def delete_tasks():
    if not tasks:
        print("There are currently no tasks.")
        print("---------------------")
        main()
    else:
        task_del = input("Enter the number of the task you wish to delete: ")
        
        print(f"Task '{tasks[int(task_del) - 1]}' has sucessfully been deleted.")
    
        del tasks[int(task_del) - 1]
        
        main()


def main():
    print("What would you like to do?")
    print("1. View Tasks")
    print("2. Add Tasks")
    print("3. Delete Tasks")
    print("4. Exit")

    choice = input("")
    
    if choice == "1":
        print("---------------------")
        view_tasks()
        
    elif choice == "2":
        print("---------------------")
        add_tasks()
        
    elif choice == "3":
        print("---------------------")
        delete_tasks()
        
    elif choice == "4":
        print("Exiting the program...")
        exit()
        
    else:
        print("Invalid input. Please try again and choose from the list of options.")
        print("---------------------")
        time.sleep(2)
        main()
        
if __name__ == "__main__":
    main()

I am actually surprised how I built this just from my knowledge, but I know it isn't perfect, and there is probably ways to clean up my code and maybe fix any bugs that could occur that I am unaware of.

sage pythonBOT
#

@pale zenith

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

devout crescent
#
def delete_tasks():
    if not tasks:
        print("There are currently no tasks.")
        print("---------------------")
        main()
    else:
        task_del = input("Enter the number of the task you wish to delete: ")
        
        print(f"Task '{tasks[int(task_del) - 1]}' has sucessfully been deleted.")
    
        del tasks[int(task_del) - 1]
        
        main()

The del tasks[int(task_del) - 1] could fail if task_del >= len(tasks)

weak parcel
#

You're treating main and the other functions like a state machine: it looks like you're "doing main", then "doing view_tasks" and then that says to "do main" again.

But in python you're doing this with function calls. A function does the stuff in the function and returns. Because each of your functions ends with a call to main (and main itself calls those funtions), none of the functions return. You're going (example):

main:
calls view_tasks
calls main
calls add_tasks
calls main
... and so on ...

It'd be better to have the functions do their thing and not call main, just return to wherever they were called from.

Then in main(), have a loop:

running = True:
while running:
    print(... the menu ...)
    choice = input("")
    if choice == "1":
        view_tasks()
    ......
    elif choice == "4":
        running = False

This way you keep offering the menu and doing the user's choice until 4, where you set the running flag to False, and then the loop ends. And main() returns.

pale zenith
#

what error exactly would it produce?

weak parcel
#

An IndexError

pale zenith
#

i tried

while task_del >= len(tasks):
            print("Please enter a value that is present in the task list.")
            task_del = input("Enter the number of the task you wish to delete: ")

but there is a type error even when I type the right number

#

wait i fixed it

#
while int(task_del) > len(tasks):
            print("Please enter a value that is present in the task list.")
            task_del = input("Enter the number of the task you wish to delete: ")
#

can someone test the full code

#
import time

tasks = []

def view_tasks():
    count = 0
    for task in tasks:
        count += 1
        print(f"#{int(count)} {task}")
        
    if not tasks:
        print("There are currently no tasks.")
        
    print("---------------------")
    main()

def add_tasks():
    task_add = input("Enter the name of your task: ").strip().lower()
    tasks.append(task_add)
    print(f"Task '{task_add}' has successfully been added to the tasks list.")
    
    print("---------------------")
    main()
 
    

def delete_tasks():
    if not tasks:
        print("There are currently no tasks.")
        print("---------------------")
        main()
    else:
        task_del = input("Enter the number of the task you wish to delete: ")
        while int(task_del) > len(tasks):
            print("Please enter a value that is present in the task list.")
            task_del = input("Enter the number of the task you wish to delete: ")
        
        print(f"Task '{tasks[int(task_del) - 1]}' has sucessfully been deleted.")
    
        del tasks[int(task_del) - 1]
    
        
        main()


def main():
    print("What would you like to do?")
    print("1. View Tasks")
    print("2. Add Tasks")
    print("3. Delete Tasks")
    print("4. Exit")

    choice = input("")
    
    if choice == "1":
        print("---------------------")
        view_tasks()
        
    elif choice == "2":
        print("---------------------")
        add_tasks()
        
    elif choice == "3":
        print("---------------------")
        delete_tasks()
        
    elif choice == "4":
        print("Exiting the program...")
        exit()
        
    else:
        print("Invalid input. Please try again and choose from the list of options.")
        print("---------------------")
        time.sleep(2)
        main()
        
if __name__ == "__main__":
    main()
#

@devout crescent

#

@weak parcel

#

@sage python

devout crescent
sage pythonBOT
#
Return statement

A value created inside a function can't be used outside of it unless you return it.

Consider the following function:

def square(n):
    return n * n

If we wanted to store 5 squared in a variable called x, we would do:
x = square(5). x would now equal 25.

Common Mistakes

>>> def square(n):
...     n * n  # calculates then throws away, returns None
...
>>> x = square(5)
>>> print(x)
None
>>> def square(n):
...     print(n * n)  # calculates and prints, then throws away and returns None
...
>>> x = square(5)
25
>>> print(x)
None

Things to note

  • print() and return do not accomplish the same thing. print() will show the value, and then it will be gone.
  • A function will return None if it ends without a return statement.
  • When you want to print a value from a function, it's best to return the value and print the function call instead, like print(square(5)).
noble wigeon
sage pythonBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.