below is my code and there are two version. First, for loop without if statement and second, for loop with if statement. From what I have found that, if I remove if statement on first version, the result will show all employees information. I'm still learning python and thanks in advance
def addNew():
global employees
newEmp = []
checkList = []
newEmp.append(input("Enter id: "))
newEmp.append(input("Enter name: "))
newEmp.append(input("Enter department: "))
newEmp.append(input("Enter position: "))
checkList.append(newEmp)
for new in checkList:
print(new)
for exist in employees:
print(exist)
result
['1001', 'das', 'das', 'das'] # from print(new)
['1000', 'tim', 'hr', 'admin'] # from print(exist)
['1003', 'jim', 'hr', 'clerk'] # from print(exist)
['1007', 'ida', 'hr', 'audit'] # from print(exist)
['1005', 'mia', 'itss', 'security'] # from print(exist)
However, on this second version code below, if I put the if statement in for loop the result will only show one employee information.
def addNew():
global employees
newEmp = []
checkList = []
newEmp.append(input("Enter id: "))
newEmp.append(input("Enter name: "))
newEmp.append(input("Enter department: "))
newEmp.append(input("Enter position: "))
checkList.append(newEmp)
for new in checkList:
print(new)
for exist in employees:
print(exist)
if new[0] == exist[0]:
print("entered id",new[0],"is already exist")
break
elif new[0] != exist[0]:
employees.extend(checkList)
break
result
['1001', 'das', 'das', 'das'] # from print(new)
['1000', 'tim', 'hr', 'admin'] # from print(exist)
-
1The for loop ends because of the break statements. Remove them if you want to go through the whole list.Heike– Heike2020年09月30日 06:46:42 +00:00Commented Sep 30, 2020 at 6:46
-
why why why. I have spend almost 2 hour how to solve this. thank you master @HeikeIzzat Rashid– Izzat Rashid2020年09月30日 06:59:58 +00:00Commented Sep 30, 2020 at 6:59
1 Answer 1
It's because it either went inside the if statement or the elif statement and since both of them have a break statement, the inner loop is terminated immediately even though not all the employees have been gone through yet.
1 Comment
break cause my program not function as I expected. thank you for your help. :)