我在编写脚本时正在学习python 3.6,我遇到了一个问题:

以下是我的代码

from sys import exit

print("Welcome to the official game designed by Prince Bhatia")
print("Copywrite @princebhatia")

def list1():
    loop = 5
    while loop == 5:

    print("Game starts here")
    list1 = ["Rahul", "Prince", "Sam", "Sonu"]
    print("which Player do you choose?")
    print("Now the game starts")
    name1 = input()

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
    else:
        print("Please enter the valid name")
    loop = 6

list1()

print("""-------------------------------------""")

但是问题是,每当我输入定义的名称时,它都可以正常工作,但是当我输入错误的名称时,它停止了,但是我想要的是,让我继续询问“请输入有效名称”,直到输入有效名称为止。 任何建议。 python 3.6

在此处留出空格以输入代码

===============>>#1 票数:1

您可以将5分配给else loop ,然后将6的分配上移到同一变量:

from sys import exit

print("Welcome to the official game designed by Prince Bhatia")
print("Copywrite @princebhatia")

def list1():
    loop = 5
    while loop == 5:

    print("Game starts here")
    list1 = ["Rahul", "Prince", "Sam", "Sonu"]
    print("which Player do you choose?")
    print("Now the game starts")
    name1 = input()

    loop = 6

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
    else:
        print("Please enter the valid name")
        loop = 5

list1()

print("""-------------------------------------""")

无论如何,改进此变量的名称和值是一个好主意。 最好在此处使用具有isInvalidName之类名称的布尔变量。 所以您while将是: while isInvalidName:

===============>>#2 票数:1 已采纳

首先,您的缩进是错误的。

问题所在:无论您是否获得匹配的答案,无论如何都将loop = 6设置为。

这里有一个稍微不同的建议:

print("Game starts here")
print("which Player do you choose?")
print("Now the game starts")

while True:

    name1 = input()

    if "Rahul" in name1 or "rahul" in name1:
        print("Rahul Enters the room1")
        break
    elif "Prince" in name1 or "prince" in name1:
        print("Prince Enters the room2")
        break
    elif "Sam" in name1 or "sam" in name1:
        print("Sam Enters the room3")
        break
    elif "Sonu" in name1 or "sonu" in name1:
        print("Sonu Enters the room4")
        break
    else:
        print("Please enter the valid name")

这样,一旦获得有效输入,我们便会中断循环,否则我们将无限期地循环。

  ask by Prince Bhatia translate from so

未解决问题?本站智能推荐: