繁体   English   中英

For loop inside while loop in asking user input with conditions

[英]For loop inside while loop in asking user input with conditions

我正在写一个 python 游戏,它有以下功能可以向用户询问。

  1. 最多可容纳 4 名玩家(最少 1 名玩家,最多 4 名玩家)
  2. 它会询问玩家姓名。 如果名字已经存在,程序会提示“名字已经在列表中”,要求重新输入名字
  3. 如果玩家在玩家名称输入中输入空字符串,它将退出。
  4. 它会询问玩家想要玩多少 n 个随机数字(使用 randint(start, stop))。 最多只允许 3 位数字

我知道我必须使用while循环无限期地询问用户输入,直到满足条件为止。 我还必须使用for循环根据第 1 点的输入要求用户输入名称。

以下是我有错误的尝试。 因此,需要您的帮助进行审核-

def attempt1():
playerList = []
numPlayers = input("How Many Players? ")
if int(numPlayers) < 5 and int(numPlayers) > 0:
    while True:
        if numPlayers != "":
            for i in range(int(numPlayers)):
                playerName = input("Player name or <Enter> to end ")
                if playerName != "":
                    if playerName not in playerList:
                        playerList.append(playerName)
                    break
                else:
                    print("Player Name Cannot be empty")
                    # numPlayers = input("How Many Players? ")
        else:
            print("There must be at least one player")
            numPlayers = input("How Many Players? ")
else:
    print("Invalid number of players. Please enter 1 - 4")
print(playerList)

def attempt2(numPlayers):
playerList = list()
# numPlayers = 1
i = 0
while i < 4:
    for x in range(0,numPlayers):
        playerName = input("Name ")
        if playerName not in playerList:
            playerList.append(playerName) 
            i += 1
        else:
            print("Name is already in the list")
print(playerList)
return playerList

这解决了我的问题。 如果您有更好的解决方案,请提出建议。 我确定我这里的代码很乱,但现在可以用了。

def askPlayerName(numPlayers):
playerList = []
x = numPlayers
while True:
    if x > 0:
        for i in range(x):
            print(x)
            playerName = input("Enter name: ")
            if playerName not in playerList:
                x -= 1
                playerList.append(playerName)
                break
            else:
                print("ELSE")
                x = numPlayers - len(playerList)
                print(x)
                print("name aldy in the list")
    else:
        return playerList
return playerList

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM