Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python skipping my if and else statement in a for loop, but the for loop is running

Well im still learning and im now into pyqt5 designer but i have a problem with a for and if statement where python dont do neither of the else or if, i use the print (empleados[i]["Nombre"]), to check if the else is running but none of the if or else run

        for i in range(0,len(empleados)):
            print(empleados[i]["Numero"])
            if self.ui.num.text() == empleados[i]["Numero"]:
                QtWidgets.QMessageBox.information(self,"Advertencia","No se pueden registrar dos numeros de empleado iguales")    
            else:
                
                empleados.append({"Nombre":self.ui.nom.text(),
                                  "Numero":self.ui.num.text(),
                                  "Salario":self.ui.salario.text(),
                                  "Dep":self.ui.dep.currentText(),
                                  "FechaC":self.ui.dateC.date(),
                                  "FechaN":self.ui.dateN.date()})
                print (empleados[i]["Nombre"])
                break

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is the intent to append a new element to empleados if and only if there isn’t any with a matching Numero? If so I think this’ll do the trick:

if any(e["Numero"] == self.ui.num.text() for e in empleados):
    QtWidgets.QMessageBox.information(
        self,
        "Advertencia",
        "No se pueden registrar dos numeros de empleado iguales"
    )
else:
    empleados.append({
        "Nombre":self.ui.nom.text(),
        "Numero":self.ui.num.text(),
        "Salario":self.ui.salario.text(),
        "Dep":self.ui.dep.currentText(),
        "FechaC":self.ui.dateC.date(),
        "FechaN":self.ui.dateN.date()
    })

In general, modifying a list as you’re iterating over it doesn’t work well, but in this case I don’t think you want to do the append inside the loop anyway, since you only want to append one element.

If Numero is unique, you might consider making empleados a dictionary keyed on that field, e.g.:

emp_by_num = {e["Numero"]: e for e in empleados}

so that you can do quick checks with in rather than having to use any:

if self.ui.num.text() in emp_by_num:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading