python不支持的操作数类型问题

时间:2013-04-04 01:29:21

标签: python

我正在为高尔夫球场编写一个用户界面,其中有一个文本文件,其中包含联盟中球员的名字。用户输入每个玩家的9个洞的分数,并返回每个玩家的总分,分数和小鸟。我收到了这个错误:

Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    main()
  File "/Users/tinydancer9454/Documents/python/golfRound.py", line 101, in main
    enterScores(l, players)
  File "/Users/tinydancer9454/Documents/python/golfRound.py", line 114, in enterScores
    p.recordScores(holeScores)
  File "/Users/tinydancer9454/Documents/python/golfRound.py", line 42, in recordScores
    self.__gross = sum(holeScores)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我真的不知道如何修复它,因为我不应该改变玩家或联盟类。

class Player:
""" Represents a player in the golf league """

    PAR = [4, 3, 4, 3, 4, 5, 4, 3, 5]
    """ par for each of the 9 holes """

    def __init__(self, name):
        """ creates a Player and keeps track of stats """
        self.__name = name
        self.__pars = 0
        self.__birdies = 0
        self.__gross = 0

    def getName(self):
        """ returns a player's name """
        return self.__name

    def getGross(self):
        """ returns a player's gross score """
        return self.__gross

    def getPars(self):
        """ returns number of pars made """
        return self.__pars

    def getBirdies(self):
        """ returns number of birdies made """
        return self.__birdies

    def recordScores(self, holeScores):
        """ mutator method that uses the results of one round of play
          (9 holes) to update a player's stats """
        self.__gross = sum(holeScores)
        self.__findparsandbirdies(holeScores)

    def __findparsandbirdies(self, scores):
        """ helper method that finds the number of pars and birdies """

        pars = 0
        birdies = 0
        hole = 0
        for score in scores:
            if score == Player.PAR[hole]:
                pars += 1
            if score == Player.PAR[hole] - 1:
                birdies += 1
            hole += 1
        self.__pars = pars
        self.__birdies = birdies

    def __str__(self):
        """ returns a string representation of a player """
        return 'a Player named ' + self.__name

class League:
""" represents the players of a golf league """

    def __init__(self, fileName = 'players.txt'):
        """ creates a list of Player objects from the
            names stored in the file specified """
        self.__playerList = []
        datafile = open(fileName, 'r')
        for line in datafile:
            playerName = line.rstrip()
            player = Player(playerName)
            self.__playerList.append(player)

    def getNumPlayers(self):
        """ returns the number of players is the league """
        return len(self.__playerList)

    def getPlayerbyPosition(self, position):
        """ returns the player at the specified position """
        return self.__playerList[position]

    def getPlayerbyName(self, name):
        """ returns the player with the specified name """
        for player in self.__playerList:
            if player.getName() == name:
                return player
        return None

    def __str__(self):
        return 'a golf league with ' + str(self.getNumPlayers()) + ' players'



def main():
    """The input and output for the program"""
    l= League()
    players= []
    enterScores(l, players, position)
    isValidScore(holeScores)
    output(players)


def enterScores(l, players, position):
    """enter the scores"""
    for position in range(l.getNumPlayers()):
        holeScores= input(("Please enter a list of the player's scores: "))
        while not isValidScore(holeScores):
            holeScores= input(("Please enter a valid list of scores: "))
        p= l.getPlayerbyPosition(position)
        players.append(p)
        p.recordScores(holeScores)


def isValidScore(holeScores):
    """checks if the scores entered for a single hole are 1 to 10, inclusive"""
    for score in holeScores:
        if score == 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 10:
            return True
        else:
            return False                


def output(grossScore, pars, birdies):
    """prints output"""
    for player in players:
        print(player.getName())
        print('Gross score:', player.getGross())
        print('Pars: ', player.getPars())
        print('Birdies: ', player.getBirdies())

1 个答案:

答案 0 :(得分:1)

如果您使用的是Python 3,holeScores是一个字符串,而不是整数。您需要将其转换为数字列表:

user_input = input("Please enter a valid list of scores: ")
holeScores = [int(score) for score in user_input.split()]

此外,此行不符合您的预期:

if score == 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 10:

它将被评估为:

if (score == 1) or (2) or ...

评估为True。只需这样做:

for score in scores:
    if not (1 <= score  <= 10):
        return False

return True