pythonstringfunctiondictionaryenumerate

Using an enumerate function for a string, with inserted file extracted variables, is it possible to recall correlated enumerate numbers upon input?


I am very new to Python, so not sure about anything:) Through defining a function, I was able to number a task, with the information extracted from a text file.

def view_mine():
  
  with open("tasks.txt", "r") as file: 
    
    for i, lines in enumerate(file):

     temp = lines.strip()

     temp = temp.split(", ")

     if user_name in (temp[0]):
         
         print("\n" + str(i+1) + ". " + f"Assigned to:\t{temp[0]}\nThe tital of the task:\t{temp[1]}\
               \nThe description of the task :\t{temp[2]}\nSet date:\t{temp[3]}\
                \nDue date:\t{temp[4]}\nTask complete? :\t{temp[5]}")
        
    file.close()

I then need to use that number, in order to ask the user to input the number of tasks he/she wishes to edit, aka change the due date/completion status.

     view_mine()

     print("\n")

     task_selection = input("Select a task for modification? (enter -1 to return to the main menu): ")

     task_selection = int(task_selection)

     task_selection = task_selection - 1

     task_selection = view_mine(task_selection) ???- here is where I am stuck 

     if task_selection != ("-1"):

        task_modification = input("Would you like to:\n1-edit the task\n2-mark the task as complete\nEneter your choice: ")

        if task_modification == ("1"):
           
           task_modification_edit = input("Would you like to:\n1-edit the username the task is assigned to\n2-edit the due date\nEnter your choice: ")

           my_task = {f"Assigned to: " : (temp[0]),
               "\nThe tital of the task: " : (temp[1]),
               "\nThe description of the task: " : (temp[2]),
               "\nSet date: " :  (temp[3]),
                "\nDue date: " :  (temp[4]),
                "\nTask complete? " : (temp[5])}

           if task_modification_edit == ("1"):
              
              task_modification_username = input("Enter the username you wish to assign the task for: ")

              my_task["Assigned to: "] = task_modification_username

              print("The uasername has been sucsessfuly changed")

           elif task_modification_edit == ("2"):
              
              task_modification_due_date = input("Please enter a new due date: ")

              my_task["\nDue date: "] = task_modification_due_date

              print ("The due date has been sucsesfully modified")

        elif task_modification == ("2"):
           
           if my_task["\nTask complete? "] == ("No"):
             
             my_task["\nTask complete? "] = ("Yes")

           print("The task has been marked as complite")

     elif task_selection == ("-1"):

        break 

I am not sure how to perform this, to get the wanted outcome of allowing the user to chose the number of the task first, and then perfom modifications on that selected task.


Solution

  • OK then...
    I'll give you a silly solution, that you can use as a starting point to built your program and start practising Python! You should change features, fix flaws, or add the necessary improvements, according to what you really want to achieve.

    Hints:

    _How to restart the program instead of quitting in case of errors?
    _How to ensure that an input is a valid integer?
    _How to handle other exceptions? (e.g. the "IndexError: list index out of range" that occurs when the number corresponds to a Task that does not exist)
    _How to check that a date format is correct?
    _How to use '-1' as command to return to main-menu for every input?
    _How to create a method that modify/update the original file after changes?
    _How to add new tasks from input?
    _How to create a simple GUI interface, instead of using terminal?

    Snippet:

    def view_mine(user_name):
        tasks = []
        
        with open("text_stack_prova.txt", "r") as file:
            for lines in file:
                temp = lines.strip().split(", ")
                if user_name == temp[0]:
                    tasks.append(temp)
            file.close()
    
        return tasks
    
    if __name__=="__main__":
        while True:
            user_name = input("Enter the user you are looking for:\n")
            tasks = view_mine(user_name)
    
            if len(tasks) == 0:
                print(f"No tasks found for user: {user_name}! Exiting program...")
                break
            else:
                print("Here are the Tasks assigned to", user_name + ":")
                for i, task in enumerate(tasks):
                    print(str(i+1) + ". " + f"Assigned to:\t{task[0]}\nThe title of the task:\t{task[1]}\
                          \nThe description of the task:\t{task[2]}\nSet date:\t{task[3]}\
                          \nDue date:\t{task[4]}\nTask complete? :\t{task[5]}\n")
    
            task_selection = input("Give me the index of the Task that need to be modified: (enter -1 to return to the main menu): ")
    
            try:
                task_selection = int(task_selection)
    
                if task_selection == -1:
                    print("Ok let's restart from the beginning...\n")
                    continue # not break!!
                else:
                    task_selection -= 1
                    selected_task = tasks[task_selection]
                    task_modification = input("Would you like to:\n1 - edit the task\n2 - mark the task as complete\nEnter your choice: ")
                    while True:
                        if task_modification == "1":
                            task_modification_edit = input("Would you like to:\n1 - edit the username the task is assigned to\n2 - edit the due date\nEnter your choice: ")
                            if task_modification_edit == "1":
                                task_modification_username = input("Enter the username you wish to assign the task to: ")
                                old_name = selected_task[0]
                                selected_task[0] = task_modification_username
                                print("The user {} has been successfully changed in {}".format(old_name, task_modification_username))
                                break
                            elif task_modification_edit == "2":
                                task_modification_due_date = input("Please enter a new due date [YYYY-MM-DD]: ")
                                selected_task[4] = task_modification_due_date
                                print("The due date has been successfully modified.")
                                break                        
                            else:
                                print("Invalid choice. Please try again.")
                                continue
                        elif task_modification == "2":
                            if selected_task[5] == "No":
                                selected_task[5] = "Yes"
                                print("The task has been marked as complete.")
                            else:
                                print("The task is already marked as complete.")
                                break
                        else:
                            print("Invalid choice. Please try again. Exiting program...")
    
            except ValueError:
                print("Invalid input. Please enter a valid number or -1.")
                break