0

Why does python prints andata/ritorno 3 times? I've tried to outdent if, but it doesnt work

listlf = []
connf = sqlite3.connect("Database.db")
coursorf = connf.cursor()
sqltf = coursorf.execute("select np,id from orari")
for lf1 in sqltf:
    lf2 = [lf1[0],lf1[1]]
    listlf.append(lf2)
for lf3 in listlf:
    if town == str(lf3[0]) and bs == str(lf3[1]):
        loc1 = listlf.index(lf3)
        for lf3 in listlf:
            if des_town == str(lf3[0]) and des_bs == str(lf3[1]):
                loc2 = listlf.index(lf3)
                if loc1 < loc2:
                    print("andata")
                else:
                    print("ritorno")

Output:

andata
andata
andata
4
  • 1
    What is the content of sqltf and therefore listlf? Commented Apr 30, 2020 at 18:07
  • It depends on the input that the user enters, I didn't put all the code because it's too long, but I know that the print depends on the sqltf list, but I don't know how to remove this dependency Commented Apr 30, 2020 at 18:10
  • Can you explain more background about what you are trying to do? Commented Apr 30, 2020 at 18:14
  • I am creating a program that tries to show the buses that pass through a city. This piece of code defines whether you are looking for the outward or return journey (in Italian l'andata is the outward journey and ritorno is the return). To define the route, I extracted all the cities from the database. The cities are sorted in the list according to the route (the first for example and where the bus leaves from). If the user enters a stop which is larger than the first one, it is return, vice versa it is the outward journey. Commented Apr 30, 2020 at 18:20

1 Answer 1

2

You have two nested loops using the same variable:

for lf3 in listlf: # lf3 !
    if town == str(lf3[0]) and bs == str(lf3[1]):
        loc1 = listlf.index(lf3)
        for lf3 in listlf: # lf3 too!

Whatever you tried to do, this seems wrong.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.