如何在功能中订购商品?

时间:2015-07-08 18:05:10

标签: python function file

对于我的计算课程,我必须创建一个算术测验,它可以将用户得分保存在文件中。我已完成此部分但是对于下一个任务,我必须按字母顺序打印用户名,并显示最高的三个分数。然后打印最高分到最低分(显示哪些用户获得了哪个分数),然后找到每个用户的平均分数,并打印从最高到最低顺序的平均分数(再次显示哪个用户得到哪个分数)。不幸的是,我不知道该怎么做。请帮我。到目前为止我的代码是:

import random
from random import randint
import math
import fileinput

question = 0
ans = 0
score = 0

firstname = input("What is your first name?")
lastname = input("What is your last name?")
classofstudent = input("Which class are you in? (1,2 or 3?)")
print ("Welcome to this arithmetic quiz")
print ("")
for question in range(10):
    def multiplication():
        global ans
        numberOne, numberTwo = random.randint(0,10), random.randint(0,10)
        print ("What is", numberOne, "*", numberTwo)
        ans = (numberOne * numberTwo)

    def subtraction():
        global ans
        numberOne, numberTwo = random.randint(0,10), random.randint(0,10)
        print ("What is", numberOne, "-", numberTwo)
        ans = (numberOne - numberTwo)

    def addition():
        global ans
        numberOne, numberTwo = random.randint(0,10), random.randint(0,10)
        print ("What is", numberOne, "+", numberTwo)
        ans = (numberOne + numberTwo)

    operation = [multiplication, subtraction, addition]
    randoperation = random.choice(operation)
print()
def main():
    question = 0
    score = 0
    randoperation = random.choice(operation)

    whileTrue:
        try:
            randoperation()
            randoperation = random.choice(operation)
            if question >= 10:
                break

            userinput = int("What is your answer?")
            if userinput = ans:
                global score
                score = score + 1
                global question
                question += 1
                print ("Your answer is correct")
            else:
                print ("Incorrect")
                question += 1
        except ValueError:
            print ("Invalid answer")
            question += 1
        while question == 10:
            print (firstname ,lastname ,"you scored" , score,"/10")
            break
def filewrite():
    fileopen = open("data.txt", "a")
    counts = str(score)
    cos = str(classofstudent)
    Textline = (firstname + " " + lastname + " / class " + cos + " /score = " + counts + "/10" + "\n")
    fileopen.write(Textline)
    fileopen.close

def read():
    with open ('data.txt') as data:
        print ("")
        for line in data:
            print (line, end ='')
        print ("")
    check = "Y"

main() 
filewrite()
read()

1 个答案:

答案 0 :(得分:0)

您可以先将结果读入列表或字典,然后使用sorted()函数按字母顺序,升序或降序排序元素。

>>> elements = [22, 333, 0, -22, 1000]
>>> print sorted(elements)
[-22, 0, 22, 333, 1000]
>>> 
>>> 
>>> for element in reversed(sorted(elements)):
...     print element
... 
1000
333
22
0
-22 

查看本教程关于Sorting