我在为无限多的玩家制作一个游戏。每个玩家将猜5个介于1和25之间的数字。(还有一些其他的要求,你会在代码中看到)我的问题是,我希望第一个用户输入他的猜测,如果他的猜测完全满足了要求,我们返回并遍历下一个玩家猜测的名字列表。问题是我不知道如何打破循环,回到“主”循环,得到下一个球员。感谢您对这个问题的建议!你知道吗
while True:
try:
for name in name_list:
guess = input("{}, Enter 5 numbers between 1 and 25 (Seperate with ','): ".format(name))
guess = guess.split(",")
guess = [int(i) for i in guess]
while True:
for i in guess:
if len(guess) != 5:
print("You need to enter 5 numbers")
guess = input("{}, Enter 5 numbers between 1 and 25 (Seperate with ','): ".format(name))
guess = guess.split(",")
guess = [int(i) for i in guess]
elif guess.count(i) > 1:
print("There can only be one of each number!")
guess = input("{}, Enter 5 numbers between 1 and 25 (Seperate with ','): ".format(name))
guess = guess.split(",")
guess = [int(i) for i in guess]
elif i > 25 or i < 1:
print("The numbers need to be between 1 and 25")
guess = input("{}, Enter 5 numbers between 1 and 25 (Seperate with ','): ".format(name))
guess = guess.split(",")
guess = [int(i) for i in guess]
else:
break
guess_list.append(guess)
print("Your numbers: " + str(guess) + "\n")
except ValueError:
print("You need to enter integers and seperate by (',')")
continue
´´´
我浏览了你的代码,其中有一些突破性的问题。我已经把他们的一个快速的总结,以及(我认为)你正试图做的正确版本。你知道吗
在循环中检查
len(guess)
时,应该在检查每个元素之前检查一次长度对于最初的问题,请看一下
input_good
变量,该变量在for循环中设置为true,如果有任何错误,则设置为False。。。这个变量会让内部while循环知道在一切正常的情况下会自行中断(因为我们一次只能直接中断一个循环)这是一个起点,接下来您应该看看如何使用函数来处理重复行为,并尽可能少地使用
try/except
代码(让catch-anywhere处理错误是一个糟糕的做法)相关问题 更多 >
编程相关推荐