簡體   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