为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_遁去的一_1 2023-02-07 17:31:02
即使我已经输入了 -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:             breakprint ("The runner-up score is:",values[1]) 这是发生了什么:Enter number of players: 3Enter scores separated by space: 10000 2 3Error. Scores should be -100 to 100 only. Please enter scores again separated by space: 233 4 5Error. Scores should be -100 to 100 only. Please enter scores again separated by space: 1 2 3Error. Scores should be -100 to 100 only. Please enter scores again separated by space:          可以看到,第三次我已经输入了1 2 3,但是还是报错。请帮助我:(非常感谢您的帮助!
查看完整描述

2 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

更改此部分:


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

到:


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

您的代码不起作用的原因是:


for x in record:

    while( x < -100 or x > 100): 

您正在循环使用那个特定的x. 更新时record,具体x内容将保持不变,因此while循环永远不会中断。


查看完整回答
反对 回复 2023-02-07
?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

这是根据您的目的编写代码的正确方法:


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。


并更改以下代码:


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

现在应该工作


查看完整回答
反对 回复 2023-02-07
  • 2 回答
  • 0 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信