【发布时间】:2020-12-21 04:21:03
【问题描述】:
我正在编写一个 python 游戏,它有以下功能可以询问用户。
- 最多可容纳 4 人(最少 1 人,最多 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
【问题讨论】:
-
你遇到什么错误可以发布错误
-
更好的编写函数,只询问一个玩家的名字 - 然后在循环中使用它,为 4 个玩家运行它。
-
您可以在开始时执行
numPlayers = int(numPlayers),然后您不必重复int(numPlayers)这么多次。代码将更具可读性。 -
@furas 所以我写了一个函数来询问用户名1次并在while循环和for循环中使用它?它适合我的第 2 点吗?
-
@deadshot 用于尝试 2,如果 numPlayers = 4 并且我输入不重复的名称,我的程序将提示用户输入 4 次。但是如果我输入重复的名字,它会提示超过4次。所以我的 len(playlist) 变成 8 应该是最小 1 或最大 4
标签: python loops for-loop input while-loop