Imran Akhter Imran Akhter - 3 months ago 9
Python Question

Continue isnt working properly

I do need help in solving my code.
Below python code 'continue' is not working properly

dicemp = {'12345':''}
while(1):
choice = int(input("Please enter your choice\n"))

if (choice == 1):
empno = input("Enter employee number: ")
for i in dicemp.keys():
if i == empno:
print("employee already exists in the database")
continue
print("Hello")


Output:

Please enter your choice

1

Enter employee number: 12345

employee already exists in the database

Hello

So for the above code if I give same employee no. 12345 it is going into if block and printing the message"employee already exists in the database" after this it should continue from start but in this case it is also printing "hello".

Answer

Your continue is moving the for loop on to its next iteration, which would have happened anyway. If you need to continue the outer loop, you can do something like this:

while True:
    choice = int(input("Please enter your choice\n"))

    if choice == 1:
        empno = input("Enter employee number: ")
        found = False
        for i in dicemp:
            if i == empno:
                print("employee already exists in the database")
                found = True
                break
         if found:
             continue
         print("Hello")

Now the continue is outside the for loop, so it will continue the outer loop.

You could simplify this to:

while True:
    choice = int(input("Please enter your choice\n"))
    if choice==1:
        empno = input("Enter employee number: ")
        if empno in dicemp:
            print("employee already exists in the database")
            continue
        print("Hello")

and get rid of the inner loop entirely.

Comments