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

即使我已经输入了 -100 到 100 之间的分数,我仍然卡住了。为什么会这样?请帮我修一下!


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]) 

这是发生了什么:


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,但是还是报错。


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


qq_遁去的一_1
浏览 115回答 2
2回答

慕盖茨4494581

更改此部分:for x in record:&nbsp; &nbsp; while( x < -100 or x > 100):&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; scores = input("Error. Scores should be -100 to 100 only. Please enter scores again separated by space: ")&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; data = list(map(int, scores.split()))&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; record = data[slice(players)]&nbsp;到:while any( x < -100 or x > 100 for x in record):&nbsp; &nbsp; &nbsp; &nbsp; scores = input("Error. Scores should be -100 to 100 only. Please enter scores again separated by space: ")&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; data = list(map(int, scores.split()))&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; record = data[slice(players)]&nbsp;您的代码不起作用的原因是:for x in record:&nbsp; &nbsp; while( x < -100 or x > 100):&nbsp;您正在循环使用那个特定的x. 更新时record,具体x内容将保持不变,因此while循环永远不会中断。

白猪掌柜的

这是根据您的目的编写代码的正确方法:players = int(input("Enter number of players: "))&nbsp;while (players < 2 or players > 10):&nbsp; &nbsp; players = int(input("Error. Players should be 2-10 only. Enter number of players: "))&nbsp; &nbsp; continue现在它会不停地问你,直到玩家人数为 2 - 10。并更改以下代码:while any(x < -100 or x > 100 for x in record):&nbsp; &nbsp; scores = input("Error. Scores should be -100 to 100 only. Please enter scores again separated by space: ")&nbsp;&nbsp; &nbsp; data = list(map(int, scores.split()))&nbsp;&nbsp; &nbsp; record = data[slice(players)]&nbsp;现在应该工作
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python