-1

I hope someone can finally help. I am trying to write code to save tasks to a text file. The text file takes input from the user and stores the info. I would like to find a very simple way to change my following code to add a number to the task so that I will be able to call on the specific task later. After the first task is labelled User assigned to task 1: the next task should be labelled User assigned to task 2: and then task User assigned to task 3:

task example:

User assigned to task:

jack

Task Title:

jog

Task Description:

Go jogging

Task Due Date:

2020-02-08

Date Assigned:

2020-02-07

Task Completed:

No

requested output:

User assigned to task 1:

jack

Task Title:

jog

Task Description:

Go jogging

Task Due Date:

2020-02-08

Date Assigned:

2020-02-07

Task Completed:

No

The code i have so far is as follows. It is writing numbers to the text file but they are all labelled task 1 and the next task is not changing to task 2:

def add_task(count):
 if menu == "a" or menu == "A":
    with open( 'user.txt' ) as fin :    
        usernames = [i.split(',')[0] for i in fin.readlines() if len(i) > 3]
        task = input ("Please enter the username of the person the task is assigned to.\n")
    while task not in usernames :
        task = input("Username not registered. Please enter a valid username.\n")

    else:
        task_title = input("Please enter the title of the task.\n")
        task_description = input("Please enter the task description.\n")
        task_due = input("Please input the due date of the task. (yyyy-mm-dd)\n")
        date = datetime.date.today()
        task_completed = False
        if task_completed == False:
            task_completed = "No"
        else:
            task_completed = ("Yes")
        with open('tasks.txt', 'a') as task1:
            count=count+1
            task1.write("\nUser assigned to task: "+ str(count) + "\n" + task + "\nTask Title :"  + "\n" + task_title + "\n" + "Task Description:\n" + task_description + "\n" + "Task Due Date:\n" + task_due + "\n" + "Date Assigned:\n" + str(date) + "\n" + "Task Completed:\n" + task_completed + "\n")
            print("The new assigned task has been saved")
count = 0
add_task(count)

1 Answers1

1

It's because the variable count is only changed within the scope of add_task(). The change is not seen outside of that function, so count is always 0 when you call add_task(count).

To learn more about scope in Python, check out this link: https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#more-about-scope-crossing-boundaries

EDIT: You can either access the global count variable (see this answer), or - and this is what I would recommend - you can return the local variable count and use it to update the other variable like this: count = add_task(count)

Owen
  • 404
  • 5
  • 13