提问者:小点点

如何使用循环将用户发送回输入? (简单)


如果p1不在“PlayerNames”列表中,我如何重复输入问题? 这是我的代码:

playernames = 'John', 'Steve', 'Mary'

p1 = str(input("What is player 1's name? "))
if p1 in playernames:
    print('Access Granted')
elif #How do I loop the player back to the start of the input?
print()

谢谢


共3个答案

匿名用户

下面是一个简单的代码。

playernames = ['John', 'Steve', 'Mary']

p1 = input("What is player 1's name? ")
while p1 not in playernames:
    print("Player not found!")
    p1 = input("What is player 1's name? ")

您的代码中有几个错误,我已经更正了:

  1. 您需要使用方括号来创建列表。 因此,playernames='John','Steve','Mary'变为playernames=['John','Steve','Mary']
  2. 您不必将输入类型转换为str,因为input()默认情况下返回字符串。

为了引起您的注意,这段代码中的另一个改进可以是处理字母情况。 例如,如果用户输入的john在您的列表中,但第一个字母不是大写的。 因此,循环不会中断并再次请求输入。

匿名用户

使用无限循环是重复输入问题的好方法。 当条件满足时(用户键入一个playernames),它将结束无限循环。

playernames = "John", "Steve", "Mary"


finished = False
while not finished:
    p1 = str(input("What is player 1's name? "))
    if p1 in playernames:
        print("Access Granted")
        finished = True

    else:
        print("Players not in playernames")
        print()

匿名用户

playernames = ['John', 'Steve', 'Mary']

while True:
    p1 = str(input("What is player 1's name? "))

    if p1 in playernames:
        break

一条线:

while input("What is player 1's name?") not in playernames: print("Input Name is not correct")