[PYTHON] About variable scope. .. ..

Launch a local server using flask Output the ToDo task web application.

After that, when I arranged the template and executed flask run, the following error occurred.

app.py


UnboundLocalError: local variable 'count' referenced before assignment

Below is an excerpt of the part that caused the error

app.py


count = 0
@app.route("/updatedone/<int:item_id>")
def update_todoitemdone(item_id):
    todolist.update(item_id)
    count = count + 1
    return render_template("showtodo.html", todolist=todolist.get_all(), result=count)

The variable count declared outside the function If you want to use it in a function, you have to declare it globally.

Below, after correction.

app.py(Revised)


count = 0
@app.route("/updatedone/<int:item_id>")
def update_todoitemdone(item_id):
    todolist.update(item_id)
    global count
    count = count + 1
    return render_template("showtodo.html", todolist=todolist.get_all(), result=count)

Every time you press done, the number will be added! (('ω') ノ


↓ Reference article ↓ ToDo list app created with VS Code and Flask


Recommended Posts

About variable scope. .. ..
Variable scope
About variable of chainer
About 2-variable, 4-branch if statement
Variable scope when using internal functions
About LangID
About CAGR
About virtiofs
About python-apt
About Permission
About sklearn.preprocessing.Imputer
About gunicorn
About requirements.txt
About locale
About permissions
About Opencv ②
About axis = 0, axis = 1
About Opencv ③
About import
About numpy
About pip
About Linux
About numpy.newaxis
About endian
About Linux
About import
About Opencv ①
About Linux
About Linux
About Linux ①
About cv2.imread
About _ and __
About wxPython
I investigated in detail about variable processing in python
A story about Go's global variables and scope
EP 15 Know How Closures Interact with Variable Scope