Python创建一个程序,用于执行和分析课程中的最终成绩

时间:2017-04-06 19:16:25

标签: python list append average min

以下是我想要做的事情 创建一个程序,对课程中的最终成绩进行分析。程序必须使用循环,并在添加时将每个成绩附加到列表中。该程序要求用户输入10名学生的最终成绩(整数百分比)。然后程序将显示以下数据:

  • 班上最高分。
  • 班上最低分。
  • 班上的平均分。

我一直在第12行收到错误,无法找出原因。

ERROR:

Traceback (most recent call last):
  File "H:/COMS-170/program7.py", line 33, in <module>
    main()

  File "H:/COMS-170/program7.py", line 12, in main
    total = sum(info)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

CODE:

def main():
    info = get_values()
    total = sum(info)
    average = total/len(info) 
    print('Highest Grade: ', max(info))
    print('Lowest Grade: ', min(info))  
    print('Average is: ', average)

def get_values():
    num_grades = 10
    #making of the list
    grades = []
   #ask the user for the info
   print('Please enter the final grades for 10 students: ')

   #put the info into the list with a loop 
   for i in range(num_grades):
   grade = input('Enter a grade: ')
   grades.append(grade)
  return grades
main()

2 个答案:

答案 0 :(得分:1)

您的解决方案需要略微更正,因为您的用户输入返回str值,并且您希望sum这些,但首先将它们转换为int,如下所示:

def main():
    info = get_values()
    total = sum(info)
    average = total/len(info) 
    print('Highest Grade: ', max(info))
    print('Lowest Grade: ', min(info))  
    print('Average is: ', average)

def get_values():
    num_grades = 10
    #making of the list
    grades = []
    #ask the user for the info
    print('Please enter the final grades for 10 students: ')

    #put the info into the list with a loop 
    for i in range(num_grades):
        grade = int(input('Enter a grade: ')) # convert the input `str` to `int`
        grades.append(grade)
    return grades
main()

此外,您应该在int转换期间注意不会发生异常,例如ValueError

希望它有所帮助!

答案 1 :(得分:0)

问题是,在您从输入中读取后,您将获得grade变量中的字符串列表。 因此,您可以使用int方法来解析输入:

from __future__ import print_function
from django.test import TestCase
from bs4 import BeautifulSoup
import re
from django.contrib.auth.models import User

VERBOSE = True


class TraverseLinksTest(TestCase):
    def setUp(self):
        # By default, login as superuser
        self.superuser = User.objects.create_superuser('superuser1', 'superuser1@example.com', 'pwd')
        if self.client.login(username="superuser1@example.com", password="pwd"):
            if VERBOSE: print('\nLogin as superuser OK')
        else:
            raise BaseException('Login failed')

    @classmethod
    def setUpTestData(cls):
        # Initialise your database here as needed
        pass

    def test_traverse_urls(self):
        # Fill these lists as needed with your site specific URLs to check and to avoid
        to_traverse_list = ['/mysite', '/mysite/sub-page']
        to_avoid_list = ['^/$', '^$', 'javascript:history\.back()', 'javascript:history\.go\(-1\)', '^mailto:.*', '.*github\.io.*']

        done_list = []
        error_list = []
        source_of_link = dict()
        for link in to_traverse_list:
            source_of_link[link] = 'initial'

        (to_traverse_list, to_avoid_list, done_list, error_list, source_of_link) = \
            self.recurse_into_path(to_traverse_list, to_avoid_list, done_list, error_list, source_of_link)

        print('END REACHED\nStats:')
        if VERBOSE: print('\nto_traverse_list = ' + str(to_traverse_list))
        if VERBOSE: print('\nto_avoid_list = ' + str(to_avoid_list))
        if VERBOSE: print('\nsource_of_link = ' + str(source_of_link))
        if VERBOSE: print('\ndone_list = ' + str(done_list))
        print('Followed ' + str(len(done_list)) + ' links successfully')
        print('Avoided ' + str(len(to_avoid_list)) + ' links')

        if error_list:
            print('!! ' + str(len(error_list)) + ' error(s) : ')
            for error in error_list:
                print(str(error) + ' found in page ' + source_of_link[error[0]])

            print('Errors found traversing links')
            assert False
        else:
            print('No errors')

    def recurse_into_path(self, to_traverse_list, to_avoid_list, done_list, error_list, source_of_link):
        """ Dives into first item of to_traverse_list
            Returns: (to_traverse_list, to_avoid_list, done_list, source_of_link)
        """

        if to_traverse_list:
            url = to_traverse_list.pop()

            if not match_any(url, to_avoid_list):
                print('Surfing to ' + str(url) + ', discovered in ' + str(source_of_link[url]))
                response = self.client.get(url, follow=True)

                if response.status_code == 200:
                    soup = BeautifulSoup(response.content, 'html.parser')

                    text = soup.get_text()

                    for link in soup.find_all('a'):
                        new_link = link.get('href')
                        if VERBOSE: print('  Found link: ' + str(new_link))
                        if match_any(new_link, to_avoid_list):
                            if VERBOSE: print('    Avoiding it')
                        elif new_link in done_list:
                            if VERBOSE: print('    Already done, ignoring')
                        elif new_link in to_traverse_list:
                            if VERBOSE: print('    Already in to traverse list, ignoring')
                        else:
                            if VERBOSE: print('    New, unknown link: Storing it to traverse later')
                            source_of_link[new_link] = url
                            to_traverse_list.append(new_link)

                    done_list.append(url)
                    if VERBOSE: print('Done')
                else:
                    error_list.append((url, response.status_code))
                    to_avoid_list.append(url)

            if VERBOSE: print('Diving into next level')
            return self.recurse_into_path(to_traverse_list, to_avoid_list, done_list, error_list, source_of_link)

        else:
            # Nothing to traverse
            if VERBOSE: print('Returning to upper level')
            return to_traverse_list, to_avoid_list, done_list, error_list, source_of_link


def match_any(my_string, regexp_list):
    if my_string:
        combined = "(" + ")|(".join(regexp_list) + ")"
        return re.match(combined, my_string)
    else:
        # 'None' as string always matches
        return True