继续无法正常工作

Continue isnt working properly

我确实需要帮助来解决我的代码。 python 下面的代码 'continue' 无法正常工作

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")

输出:

请输入您的选择

1

输入员工编号:12345

员工已存在于数据库中

你好

所以对于上面的代码,如果我给同一个员工编号。 12345 它将进入 if 块并打印消息 "employee already exists in the database" 在此之后它应该从头继续但在这种情况下它也会打印 "hello".

您的 continue 正在将 for 循环移动到下一次迭代,这无论如何都会发生。如果你需要继续外循环,你可以这样做:

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")

现在 continuefor 循环之外,所以它将继续外循环。

您可以将其简化为:

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")

并完全摆脱内循环。