while循环没有给出预期的结果

时间:2017-07-08 15:17:36

标签: while-loop python-3.6

我正在学习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

这里给出了打算输入代码的意图空间

2 个答案:

答案 0 :(得分:1)

您可以在else中为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("""-------------------------------------""") 分配5,并将6的分配上移到同一个变量:

while

无论如何,改善这个变量的名称和值是个不错的主意。最好在这里使用一个名为isInvalidName的布尔变量。因此,您while isInvalidName:将是:import re pattern = re.compile(r"[A-Z][a-z]+|\d+|[A-Z]+(?![a-z])") def split_hashtag(tag): return pattern.findall(tag)

答案 1 :(得分: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")

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