def __init__(self):
self.planets = ['Mercury', 'Venus', 'Mars',
'Jupiter', 'Saturn','Uranus',
'Neptune', 'Pluto']
self.planets[0] = 0.38
self.planets[1] = 0.91
self.planets[2] = 0.38
self.planets[3] = 2.34
self.planets[4] = 0.93
self.planets[5] = 0.92
self.planets[6] = 1.12
self.planets[7] = 0.62
def calculate_spaceweight(self, weight):
for i in range(len(self.planets)):
print("your weight on", self.planets[i], " is", weight * self.planets[i] )
if __name__ == '__main__':
weight = float(input("what is your Earthly weight: "))
obj1 = Planet()
print(obj1.calculate_spaceweight(weight))
Run Code Online (Sandbox Code Playgroud)
输出是错误的,我知道有更好的方法来初始化列表中的值,但我不知道如何实现。这是它的输出:
your weight on 0.38 is 57.0
your weight on 0.91 is 136.5
your weight on 0.38 is 57.0
your weight on 2.34 is 351.0
your weight on 0.93 is 139.5
your weight on 0.92 is 138.0
your weight on 1.12 is 168.00000000000003
your weight on 0.62 is 93.0
None
Run Code Online (Sandbox Code Playgroud)
好的,我做了编辑,所以它现在输出正确的答案
小智 5
当你使用
self.planets[0] = 0.38
Run Code Online (Sandbox Code Playgroud)
您正在将 0.index "Mercury" 更改为 0.38
如果你想要更正确的方法,你可以使用这样的字典
self.planets = {"Mercury": 0.38, "Venus": 0.91}
Run Code Online (Sandbox Code Playgroud)
和 for 循环
for planet_name, planet_arg in self.planets.items():
print("your weight on", planet_name, " is", weight * planet_arg)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
75 次 |
最近记录: |