Narac Snave
Narac Snave

Reputation: 23

Python Mulitple For loops with common else

my code at the minute has 2 lists Exercise and Weight. These both contain the contents of generated entry boxes. When the lists are being saved to the database I need to make sure that no empty boxes are submitted, to solve this I am writing a validation algorithm to check if any of the boxes are empty, this is the code so far:

for item in Exercise:
    if item == '':
        self.CreateError.configure(fg = "red")
        connection.commit()

for item in Weight:
    if item == '':
        self.CreateError.configure(fg = "red")
        connection.commit()
else:
    values = zip(Exercise, Weight, ID)
    cursor.executemany("INSERT INTO Exercises(Exercise, Weight, ID) VALUES(?, ?, ?)", values)        
    connection.commit()

My problem is that I have two for loops which both have the same else. However I do not know how to create this so the else is activated if either of both of the items in the list are empty.

Upvotes: 0

Views: 51

Answers (3)

sshashank124
sshashank124

Reputation: 32189

A better approach is to use the any function:

if any(i == '' for i in Exercise) or any(i == '' for i in Weight):
    self.CreateError....
else:
    values = zip(...

The downside to this approach is that it may not be the most scalable if you have to iterate through even more collections (in addition to Exercise, Weight, etc.). However, a variation of this style could remedy that (EDIT: look at @Thierry Lathuille's answer)

Upvotes: 1

Bakuutin
Bakuutin

Reputation: 291

You can use any here

if any(item == '' for item in Exercise) or any(item == '' for item in Weight):
    self.CreateError.configure(fg = "red")
else:
    values = zip(Exercise, Weight, ID)
    cursor.executemany("INSERT INTO Exercises(Exercise, Weight, ID) VALUES(?, ?, ?)", values)        
connection.commit()

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

As you test the same conditions on the items of Exercise and Weight, you could do it like this:

from itertools import chain

if any(item == '' for item in chain(Exercise, Weight)):
    self.CreateError.configure(fg = "red")
    connection.commit()

else:
    values = zip(Exercise, Weight, ID)
    cursor.executemany("INSERT INTO Exercises(Exercise, Weight, ID) VALUES(?, ?, ?)", values)        
    connection.commit()

Upvotes: 3

Related Questions