首页 > 解决方案 > 不断循环python代码,所以它不会结束

问题描述

我试图做到这一点,即使在我向“输入命令”提供输入之后,代码也会让我回到显示最后输入的内容后提供输入的选项。例如,我希望它在之前完成后不断显示“输入命令”提示。有没有办法让代码在没有结束的情况下循环回来?

c1 = "p"
c2 = "d"
c3 = "t"

command = ""
while command != c1:
    print("Enter a command: ")
    print ("(P)profile / (D)data ")
    command = input()
    if command == c1 or command == c2:
        print ("loading...")

        time.sleep(3)

        if command == c1:
            print ("User: Student")
        if command == c2:
            print ("ID: 111111111")

        time.sleep(1)  

    print ("Enter a command: ")
    print ("(P)profile / (D)data ")
    command = input()

标签: pythonloops

解决方案


将所有内容放在一个while True循环中并删除您正在打印并要求输入的最后 3 行(因为您已经在开始时要求输入)这应该有效:

c1 = "p"
c2 = "d"
c3 = "t"

while True:
    print("Enter a command: ")
    print ("(P)profile / (D)data ")

    command = input()
    if command == c1 or command == c2:
        print ("loading...")

        time.sleep(3)

        if command == c1:
            print ("User: Student")
        if command == c2:
            print ("ID: 111111111")

        time.sleep(1)

推荐阅读