Python To-Do List List/Loops

280 views Asked by At

Been having some trouble with trying to make this to do list code. I'm trying to Write a program that will prompt the user to enter an item for their to-do list. Each item is then added to a list. When the user enters no input, the program will display the to-do list in two columns. The thing is though the input loop should have a try/except block where the block drops from the loop. should look something like this in the beginning: (spacing is weird here i know how to space in pyscriptor properly)

try:                                                                                                  
    item = input('Enter an item for your to-do list. ' + \                                        
                 'Press <ENTER> when done: ') 
             *… Python code …*                                                    
    if len(item) == 0:                                                                                   
  *#Needed to break out of the loop in interactive mode*                                              
      break 
except EOFError:    
   break 

Would be extremely helpful if anyone has any tips even on what to start with it.

1

There are 1 answers

0
Granitosaurus On BEST ANSWER

Lets try to separate this into steps:

  1. You want an endless loop that breaks on command?

    while True:
    

    fortunately terminals and python interpreter already provides process-kill break when you press Ctrl+C, so you don't need to implement that. However if you want to do some destruction clean up you can catch KeyboardInterrupt:

    try:
        while True:
    except KeyboardInterrupt:
        print('exiting program, bye!')
        sys.exit(0)
    
  2. Then you want input in every loop iteration

    while True:
        inp = input('what do?')
    
  3. Finally you determine action based on input:

    TODO = []
    
    while True:
        inp = input('add task: ')
        if not inp.strip():
            for task in TODO:
                print(f'- {task}')
        else:
            TODO.append(inp)
    

The program above will print tasks when input is empty, otherwise add input to todo list. You can exit the program by pressing Ctrl+C