设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 4352|回复: 2
打印 上一主题 下一主题

list index out of range

[复制链接]

2

主题

0

好友

16

积分

新手上路

Rank: 1

跳转到指定楼层
楼主
发表于 2017-9-16 21:05:16 |只看该作者 |倒序浏览
from random import randint

name = input('please inter your name: ')

f = open('game.txt')
lines = f.readline()
f.close()

scores = { } #初始化一个字典
for l in lines:
    s = l.split() #把每一行的数据拆分成list
    scores[s[0]] = strs[1:] #第一项作为key,剩下的作为value IndexError: list index out of range
score = scores.get(name) #查找当前玩家的分数
if score is None:
    score = [0,0,0]      #如果没有这个玩家,则新建一组数据

game_times = int(score[0])
min_times = int(score[1])
total_times = int(score[2])

print(game_times)
print(min_times)
print(total_times)

if game_times>0:
    average_times = float(total_times)/game_times
else:
    average_times = 0

print('%s,you have already played %d times,\
    at least %d times to get the number,\
    at average %.2f times to get the number'%(name,game_times,min_times,average_times))

num = randint(1,50)
print("guess what i think? it's a number between 1 to 50")
bingo = False
times = 0
while bingo == False:
    answer = input()
    answer = int(answer)
    times = times+1
    if answer<num:
        print('too small, guess again')
    if answer>num:
        print('too big, guess again')
    if answer == num:
        print('bingo!')
        bingo = True

if game_times == 0 or times < min_times:
    min_times = times
total_times += times
game_times += 1

scores[name] = [str(game_times), str(min_times), str(total_times)]
result = '' #初始化一个空字符,用来存储数据

#把成绩按照 "name  game_times  min_times  total_games"格式化
for n in scores:
    line = n + ' '+ ' '.join(scores[n])+'\n'
    result += line

f = open('game.txt','w')
f.write(result)
f.close()

这是运行结果
回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

沙发
发表于 2017-9-16 23:42:42 |只看该作者
这样看不出来的。你需要去看你的文件内容是否正常
然后再报错之前,把 scores,s,s[0] 这几个值都print出来看是否正常
这是调试代码的基本思路
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

2

主题

0

好友

16

积分

新手上路

Rank: 1

板凳
发表于 2017-9-17 10:17:04 来自手机 |只看该作者
好的,谢谢!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-4-27 01:07 , Processed in 0.027737 second(s), 24 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部