首页 > 解决方案 > Python初学者的问题

问题描述

所以我做了3个游戏并试图将它们合并在一起,但第一个有问题。

这是合并前的游戏

def Average_Game(arg , *list):

    result = arg

    for var in list:
        result = result + var

    print(result)

    print(result/len(list))

然后我在这里尝试过,但它一直给我错误

class Game:

    def __init__(self):
        print('Welcome to the Full Game')
        print('Please choose the Game you want to play')
        print('Press[1] for Average Game')
        print('Press[2] for MultiblicationTable Game')
        print('Press[3] for Even-Odd Game')

        self.choices()


    def choices(self):
        while True:
            your_choice = input('Please Enter your Choice : ')

            try:
                your_choice = int(your_choice)

                if your_choice == 1:
                    self.Average_Game()

            except ValueError:
                Print('Please enter a valid number')    

    #############################################################################

    def Average_Game(self , *list):

        result = self

        for var in list:
            result = result + var

        print(result)

        print(result/len(list))

        game1 = Game()

它给了我这个错误,我无法理解

Traceback (most recent call last):

 File "C:/Python34/Full Game 2.py", line 43, in <module>
    game1 = Game()

 File "C:/Python34/Full Game 2.py", line 10, in __init__
    self.choices()

  File "C:/Python34/Full Game 2.py", line 21, in choices
    self.Average_Game()

  File "C:/Python34/Full Game 2.py", line 37, in Average_Game
    print(result/len(list))

TypeError: unsupported operand type(s) for /: 'Game' and 'int'

标签: python

解决方案


我不确定你不能理解什么。该消息告诉您您正在尝试将游戏除以 Average_Game 中的整数,以及在哪里删除不相关的位:

    def Average_Game(self , *list):
        result = self
        print(result/len(list))

意味着您试图除以selflen(list)并且因为Average_Game是类的方法,所以是Gameself的实例Game

我不知道这应该是什么,但我认为result应该是所有的总和???在list,因此你应该有

        result = 0

        for var in list:
            result = result + var

要不就

        result = sum(list)

此外,您没有处理list空的情况,在这种情况下,您将执行0/0which... 不起作用。

顺便说一句,您的list参数:

  • 真的不应该被称为列表:除了这个名字没有解释它的目的或语义之外,它list一个内置的,它是一种不好的风格(并且有风险)隐藏这些
  • 甚至不是一个列表,star-args 被收集为一个元组
  • 没有理由成为star-arg,它应该只是一个常规参数

推荐阅读