How to access a variable declared inside IF statement outside IF statement in Python

  flask, mysql, mysql-connector, python, variables

I’m trying to use searchedInput outside my if statement so I could use the variable inside my query. but it gives me an error of UnboundLocalError: local variable 'searchedInput' referenced before assignment

@app.route('/ML', methods=['GET', 'POST'])
def index():
  if request.method == "POST":
        request_data = json.loads(request.data)
        searchData = (request_data['content'])
        searchedInput = jsonify(searchData)
        return searchedInput
  mycursor = mydb.cursor(dictionary=True)
  query = "SELECT * Companies WHERE COMPANY_NAME LIKE %s LIMIT 20;"
  mycursor.execute(query,("%" + searchedInput + "%",))
  myresult = mycursor.fetchall()

I’ve also tried declaring searchedInput just above my if statement. it removes the error but the value isn’t changed by my if statement. It stays just how I declared it. I appreciate any help anyone could give. Thank you in advance.

Source: Python Questions

LEAVE A COMMENT