I'm trying to iterate through an array to compare with an inputted value to see if that value is already in the array or not.
I do this by iterating through the array and comparing each index to the input with a for loop and an if statement.
Since this is all done on one page my issue is that my for loop only iterates through the first value in the array so it only compares the first value in the array with my input, but I need it to check through all the other values before moving onto my else statement. To input data I need to press the back button to go back to the input field which resets my for loop but I'm not sure how I should implement my comparison feature because of this.
#prev is my array and _tag holds my input
for i in range(0, len(prev)):
if _tag == prev[i]:
return render_template('back.html')
else:
query = """INSERT INTO tag (tag_value, tag_time) VALUES ('{}','{}')""".format(_tag,timestamp)
cursor.execute(query)
dataBase.commit()
cursor.execute("""SELECT * FROM tag;""")
data = cursor.fetchall()
return render_template('table.html', data=data)
CodePudding user response:
Instead of a for loop, try this
#checks if your input is in the array
if _tag in prev:
return render_template('back.html')
else:
query = """INSERT INTO tag (tag_value, tag_time) VALUES ('{}','{}')""".format(_tag,timestamp)
cursor.execute(query)
dataBase.commit()
cursor.execute("""SELECT * FROM tag;""")
data = cursor.fetchall()
return render_template('table.html', data=data)
CodePudding user response:
You have return
in if
-branch and else
-branch. return
stops execution of a function and returns you to the place where the function was called.