python - 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'
解决方案
我不确定你不能理解什么。该消息告诉您您正在尝试将游戏除以 Average_Game 中的整数,以及在哪里删除不相关的位:
def Average_Game(self , *list):
result = self
print(result/len(list))
意味着您试图除以self
,len(list)
并且因为Average_Game
是类的方法,所以是Game
类self
的实例Game
。
我不知道这应该是什么,但我认为result
应该是所有的总和???在list
,因此你应该有
result = 0
for var in list:
result = result + var
要不就
result = sum(list)
此外,您没有处理list
空的情况,在这种情况下,您将执行0/0
which... 不起作用。
顺便说一句,您的list
参数:
- 真的不应该被称为列表:除了这个名字没有解释它的目的或语义之外,它
list
是一个内置的,它是一种不好的风格(并且有风险)隐藏这些 - 甚至不是一个列表,star-args 被收集为一个元组
- 没有理由成为star-arg,它应该只是一个常规参数
推荐阅读
- python - 如果一列包含指定列表中的某些值,如何在熊猫数据框中删除行
- python - Pytest 使用夹具参数化测试
- c++ - 无法将 std::array 容器拆分为 2 个子部分
- amazon-web-services - 用于生产 EC2 的 Docker
- c++ - 作为 `const&` 轻量级对象传递
- ios - UISearch 在使用 Swift 5 的 UITableview 中不起作用
- python - DoesNotExist at /admin/login/ 站点匹配查询在 wagtail 中不存在
- python - 如何从图中计算不同排列的最小排除项?
- caching - 顺序访问数据以避免缓存未命中的示例?
- scheme - 符号和它的名称有什么区别?