【问题标题】:My program continues to say list index out of range我的程序继续说列表索引超出范围
【发布时间】:2014-04-29 01:27:31
【问题描述】:
print "Ready For the Sports Trivia Game"
print 
print
import random
print "What sport would you like to be tested on"
print "Press 1 for Baseball"
print "Press 2 for Basketball" 
print "Press 3 for Hockey" 
choice = input()
answers = []


questions = open("questionsreadin.txt", "r")
lines = questions.readlines() 
print lines
print len(lines)
questions.close()
"string \n".strip();


ans = open("answersreadin.txt","r")
lines2 = ans.readlines()
print lines2
print len(lines2)
ans.close()
#"string \n".strip();
'''
questions1 = open("questionsreadin.txt", "r")
lines1 = questions1.readlines() 
print lines1
print len(lines1)
questions1.close()
"string \n".strip();

ans1 = open("answersreadin.txt","r")
lines3 = ans1.readlines()
print lines3
print len(lines3)
ans1.close()
#"string \n".strip();

questions4 = open("questionsreadin.txt", "r")
lines4 = questions4.readlines() 
print lines4
print len(lines4)
questions4.close()
"string \n".strip();

ans4 = open("answersreadin.txt","r")
lines5 = ans4.readlines()
print lines5
print len(lines5)
ans4.close()
#"string \n".strip();
'''

if choice == 1:
    for i in range(4): 
        questions = random.randint(0,3)
        if questions == 0:
            print "What is the name of the Toronto baseball team?"
            ans = raw_input()
            if ans == answers[0]:
                print True
                answers.pop(0)
                print answers
            else:
                print False 

        if questions == 1:
            print "Who won the last world series?"
            ans1 = raw_input()
            if ans1 == answers[1]:
                print True 
                answers.pop(1)
                print answers 
            else:
                print False  

        if questions == 2:
            print "How many baseball teams are in the MLB?" 
            ans2 = input() 
            if ans2 == answers[2]:
                print True 
                answers.pop(2)
            else:
                print False 

        if questions == 3:
            print "Who was the first African American MLB player?"
            ans3 = raw_input() 
            if ans3 == answers[3]:
                print True
                answers.pop(3)
            else:
                print False 

【问题讨论】:

  • 能否提供完整的追溯信息?如果您正确格式化代码也会有所帮助。
  • 如果您解释一下您在做什么、您期望什么以及您正在获得什么,这也会有所帮助。一个更简单、更简短的示例也会有所帮助。
  • 删除注释掉的代码是最小化示例的良好开端。

标签: python list python-multithreading


【解决方案1】:

您的answers 列表为空,任何时候您尝试从中引用一个元素(answers[0]answers[1] 等)都会出现此异常。

您需要先用值填充它,可能从答案文件中填充它。你可能想要

answers = lines2

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 2021-10-15
    • 2018-12-16
    • 2011-06-14
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多