首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么即使我已经满足了条件,我也会陷入循环?

为什么即使我已经满足了条件,我也会陷入循环?
EN

Stack Overflow用户
提问于 2020-06-28 01:05:21
回答 2查看 46关注 0票数 0

即使我已经输入了从-100到100的分数,我仍然卡住了。为什么会这样呢?请帮我把它修好!

代码语言:javascript
复制
players = int(input("Enter number of players: ")) 

while (players < 2 or players > 10): #Limits number of players to 2-10 only
    players = int(input("Error. Players should be 2-10 only. Enter number of players: "))

scores = input("Enter scores separated by space: ") 
data = list(map(int, scores.split())) 
record = data[slice(players)] 

for x in record:
    while( x < -100 or x > 100): 
        scores = input("Error. Scores should be -100 to 100 only. Please enter scores again separated by space: ") 
        data = list(map(int, scores.split())) 
        record = data[slice(players)] 

record.sort(reverse= True) 


values = [] 

for x in record:
    if x not in values: 
        values.append( x )
        if len(values) == 3: 
            break

print ("The runner-up score is:",values[1]) 

这就是发生的事情:

代码语言:javascript
复制
Enter number of players: 3
Enter scores separated by space: 10000 2 3
Error. Scores should be -100 to 100 only. Please enter scores again separated by space: 233 4 5
Error. Scores should be -100 to 100 only. Please enter scores again separated by space: 1 2 3
Error. Scores should be -100 to 100 only. Please enter scores again separated by space:          

如你所见,第三次我已经输入了1 2 3,但它仍然显示错误。

请帮帮我:(非常感谢你的帮助!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-28 02:11:49

更改此部分:

代码语言:javascript
复制
for x in record:
    while( x < -100 or x > 100): 
        scores = input("Error. Scores should be -100 to 100 only. Please enter scores again separated by space: ") 
        data = list(map(int, scores.split())) 
        record = data[slice(players)] 

至:

代码语言:javascript
复制
while any( x < -100 or x > 100 for x in record):
        scores = input("Error. Scores should be -100 to 100 only. Please enter scores again separated by space: ") 
        data = list(map(int, scores.split())) 
        record = data[slice(players)] 

你的代码不能工作的原因是:

代码语言:javascript
复制
for x in record:
    while( x < -100 or x > 100): 

您正在使用该特定的x进行循环。当record更新时,该特定的x将保持不变,因此,while循环永远不会中断。

票数 1
EN

Stack Overflow用户

发布于 2020-06-28 01:22:51

这是编写代码的正确方式:

代码语言:javascript
复制
players = int(input("Enter number of players: ")) 

while (players < 2 or players > 10):
    players = int(input("Error. Players should be 2-10 only. Enter number of players: "))
    continue

现在它会没完没了地问你,直到玩家数量是2- 10。

并更改以下代码,如下所示:

代码语言:javascript
复制
while any(x < -100 or x > 100 for x in record):
    scores = input("Error. Scores should be -100 to 100 only. Please enter scores again separated by space: ") 
    data = list(map(int, scores.split())) 
    record = data[slice(players)] 

现在应该可以工作了

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62613058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档