【问题标题】:The program will not let me get the last three scores of each student程序不会让我得到每个学生的最后三个分数
【发布时间】:2015-04-29 08:07:41
【问题描述】:
print("Hello, and welcome to the Maths quiz!")

#Asks user for name
name = input("What is your name? ")

class_number = input("What is your class number? Class 1, 2 or 3? Please enter an integer, no letters.")

#This will import random to generate random functions
import random

#This is a variable for score
#It has been set to 0 at the start of the program
score = 0

scores={}
scores[name]=[]

#This creates an array containing the mathematical operators
#that this quiz will use
ops = ['+','-','*']

#A loop has been set for 0 - 10
for x in range(10):
    #This is variable has been set to the operator of the equation that
    #uses the random function and will choose a random operator from the
    #array containing the operators made earlier
    op = random.choice(ops)
    #The if statement checks if the operation is an addition operation
    if op == '+':
        #This will generate a random number between 1 and 100
        #for the first integer
        first1 = random.randint(1,100)
        #This will generate a random number between 1
        #and 100 for the first integer
        second1 = random.randint(1,100)
        #This print function will generate a mathematical question
        print ("What is " + (str(first1) + op + str(second1) + "?"))
        #This eval function will generate the answer to the mathematical
        #question asked and store it in the answer variable
        answer  = eval(str(first1) + op + str(second1))
        #This will loop the try statement until an integer is entered as the guess variable
        while True:
            #The try statement will see if the guess variable is given an integer value,
            #if not then it will print "You did not enter an integer. This is not a
            #valid answer
            try:
                #This will allow the user to enter their answer and
                #store it in the guess variable
                guess = int(input(""))
                #This will break the while loop if an integer is entered as the guess variable
                break
            except ValueError:
                print("You did not enter an integer. This is not a valid answer. Please enter a valid integer")
                print("Answer the quesiton appropiately. " + "What is " + (str(first1) + op + str(second1)) + "?")
        if guess == answer:
            #If the guess1 variable is equal to the answer1 variable, then
            #"Correct!" will be printed and one point would be
            #added to the score
            print("Correct!")
            score += 1
        else:
            #If the guess variable is equal to the answer variable, then
            #"Correct!" will be printed and one point would be
            #added to the score
            #Else "Incorrect" would be printed
            print("Incorrect")
    #The elif statement checks if the operation is a subtraction operation
    elif op == '-':
        #This will generate a random number between 1 and 20 (because over 20 could be too hard for the students)
        #for the first integer and stores it as the left2 variable
        first2 = random.randint(1,20)
        #This will generate a random number between 1
        #and 20 (because over 20 could be too hard for the students) for the second integer and stores it as the right2 variable
        second2 = random.randint(1,20)
        #This print function will generate a mathematical question
        print ("What is " + (str(first2) + op + str(second2) + "?"))
        #This eval function will generate the answer to the mathematical
        #question asked and store it in the answer1 variable
        answer1 = eval(str(first2) + op + str(second2))
        #This will loop the try statement until an integer is entered as the guess1 variable
        while True:
            #The try statement will see if the guess variable is given an integer value,
            #if not then it will print "You did not enter an integer. This is not a
            #valid answer
            try:
                #This will allow the user to enter their answer and
                #store it in the guess1 variable
                guess1 = int(input(""))
                #This will break the while loop if an integer is entered as the guess1 variable
                break
            except ValueError:
                print("You did not enter an integer. This is not a valid answer. Please enter a valid integer")
                print("Answer the question appropiately. " + "What is " + (str(first2) + op + str(second2)) + "?")
        if guess1 == answer1:
            #If the guess1 variable is equal to the answer1 variable, then
            #"Correct!" will be printed and one point would be
            #added to the score
            print("Correct!")
            score += 1
        else:
            #Else "Incorrect" would be printed
            print ("Incorrect")
    #The second elif statement checks if the operation is a multiplication
    #operation
    elif op == '*':
        #This generates the first number as a random number between
        #1 and 12 (because the students would be tested on their multiplication table)
        #used in the multiplication calculation
        #and stores it as the left3 variable
        first3 = random.randint(1,12)
        #This generates the second number as a random number between
        #1 and 12 (because the students would be tested on their multiplication table)
        #used in the multiplication calculation
        #and stores it as the left3 variable
        second3 = random.randint(1,12)
        #This generates the multiplcation question
        print ("What is " + (str(first3) + op + str(second3) + "?"))
        #This creates the answer for the multiplication question and
        #stores it as the answer2 variable
        answer2 = eval(str(first3) + op + str(second3))
        #This will loop the try statement until an integer is entered as the guess2 variable
        while True:
            #The try statement will see if the guess variable is given an integer value,
            #if not then it will print "You did not enter an integer. This is not a
            #valid answer
            try:
                #This allows the user to enter their own answer and store it as
                #the guess2 variable
                guess2 = int(input(""))
                #This will break the while loop if an integer is entered as the guess2 variable
                break
            except ValueError:
                print("You did not enter an integer. This is not a valid answer. Please enter a valid integer.")
                print("Answer the quesiton appropiately. " + "What is " + (str(first3) + op + str(second3)) + "?")
        #The if statement checks if the answer the user entered is equal
        #to the answer of the question
        if guess2 == answer2:
            #If the guess2 variable is equal to the answer2 variable, then
            #"Correct!" will be printed and one point would be
            #added to the score
            print("Correct!")
            score += 1
        else:
            #Else "Incorrect" would be printed
            print ("Incorrect")
    else:
        #Else if the operation is not an addition, subtration or multiplcation
        #operation then the break statement would be enacted and the
        #the whole if statement would stop. However, this
        #will be unlikely to happen since an operation would be chosen
        #by the program
        break 
#This will print out the user's score out of 10
print ("You got " + str(score) + "/10, " + name + " " + "from class " + class_number)

#This will create a new variable that connects both the class_number variable and
#the "Class" string so it would come out as "Class class_number".
class_tag = "Class "+ class_number

#This will create and open a new text file under the name
#of the class_tag variable.
file = open(class_tag + ".txt", "a")
#This will write down the user's name and their score
file.write(str(name) + " scored " + str(score))
#This will create a new line for each user
file.write("\n")
#This will close the file.
file.close()

user_scores = {}
user_scores[name].append(score)
for line in scores:
    name, score = line.rstrip('\n').split(' - ')
    score = int(score)
    if name not in user_scores or user_scores[name] < score:
        user_scores[name] = score
for name in sorted(user_scores):
    print(name, '-', user_scores[name])
print(user_scores[name][-3:])

我创建了一个程序,允许学生进行测验,他们的分数存储在基于他们班级的文本文件中。我正在尝试使用文本文件从中获取数据,并按照他们最后三个的条款对他们的分数进行排序,以便用户可以使用它。但是,当我尝试时:

user_scores = {}
#This adds to the list of names
user_scores[name].append(score)
for line in scores:
    name, score = line.rstrip('\n').split(' - ')
    score = int(score)
    if name not in user_scores or user_scores[name] < score:
        user_scores[name] = score
for name in sorted(user_scores):
    print(name, '-', user_scores[name])
print(user_scores[name][-3:])

IDLE shell 返回: user_scores[name].append(score) KeyError: '学生'

Class 0 文本文件的数据是:

student scored 3
student scored 8
student scored 0
student scored 4
student scored 10
student scored 3
student scored 0
student scored 4

Class 3 文本文件的数据是:

katy scored 0
katy scored 2
katy scored 0
katy scored 6

user_scores 将是一个完整的列表,因此每个名称都有一个分数列表。

更新: 我试过了:

user_scores = []
user_scores[name].append(score)
for line in scores:
    name, score = line.rstrip('\n').split(' - ')
    score = int(score)
    if name not in user_scores or user_scores[name] < score:
        user_scores[name] = score
for name in sorted(user_scores):
    print(name, '-', user_scores[name])
print(user_scores[name][-3:])

但是 IDLE shell 声明:

    user_scores[name].append(score)
TypeError: list indices must be integers, not str

那么我将如何让程序根据学生的姓名获取学生的最后三个分数?我尝试了许多其他方法,但都没有奏效。

【问题讨论】:

  • 不要重复:这三个 if-op-Block 有什么区别?写一个函数,把不同的参数放在参数里,就用这个函数。
  • 使用.format 进行字符串格式化,而不是str+
  • 不要使用eval。代码难以维护,无法检测到错误。

标签: python list file text


【解决方案1】:

这里:

user_scores = {}
user_scores[name].append(score)

您正在尝试将项目附加到列表中,但 user_scores[name] 不是列表,因为 user_scores 是一个空字典。

如果您想要一些快速而肮脏的东西,可以满足您的需求,那么:

user_scores = {}

for line in scores:
    name, score = line.rstrip('\n').split(' scored ')
    score = int(score)
    if name not in user_scores:
        user_scores[name] = []
    user_scores[name].append(score)

for name in sorted(user_scores.keys()):
    print(name + '-' + user_scores[name])

print(user_scores[name][-3:])

您的代码存在多个问题,但这样的事情至少会为您提供所需的输出。为了保持一致性,我保留了您之前在代码中使用的打印语法,但如前所述,您应该使用其他技术。

【讨论】:

  • 那么,我该怎么处理它呢?如何使 user_scores 成为列表而不是字典?我应该尝试:'user_scores = []'?
  • 很抱歉,您能否准确说明您希望您的代码做什么?到目前为止我收集的是: 1. 询问用户名。 2. 询问用户等级。 3. 给用户一个 10 个问题的测验,并跟踪用户得分。 4. 将用户分数添加到用户班级的文本文件中。 5. ???用户参加测试后,您究竟想向用户输出什么?
  • 然后输出用户最后三个分数。但是,用户可以根据调用的用户类别找到任何用户的分数及其存储在文本文件中的分数。
  • 我修改了我的答案。我假设您想要一些可以正常工作的东西。正如其他人之前提到的,您的代码存在多个问题,但这可能有效。
  • collections.defaultdict 可以让这段代码更简单一些。
猜你喜欢
  • 1970-01-01
  • 2020-07-20
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多