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
CodePudding user response:
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: