0

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)
asked Sep 30, 2020 at 6:42
2
  • 1
    The for loop ends because of the break statements. Remove them if you want to go through the whole list. Commented Sep 30, 2020 at 6:46
  • why why why. I have spend almost 2 hour how to solve this. thank you master @Heike Commented Sep 30, 2020 at 6:59

1 Answer 1

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.

answered Sep 30, 2020 at 6:47
Sign up to request clarification or add additional context in comments.

1 Comment

shame on me. why can't I saw this break cause my program not function as I expected. thank you for your help. :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.