![](/img/trans.png)
[英]Asking for user input between 2 genders using a while loop and to be stored in a variable?
[英]For loop inside while loop in asking user input with conditions
我正在寫一個 python 游戲,它有以下功能可以向用戶詢問。
我知道我必須使用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.