我该如何处理int()的这个无效文本(基数为10)错误


import math
# The standard gravitational parameter for the sun
mu = 1.327 * math.pow(10, 20)
class Planet:
def __init__(self, name, radius, moons, orbital_radius):
self.name = name
self.radius = radius
self.moons = moons
self.orbital_radius = orbital_radius
def collide(self):
self.moons = self.moons + 1
return self.moons

def volume(Planet):
v = (4 / 3) * math.pi * math.pow(Planet.radius, 3)
return str(v)
def surface(Planet):
area = 4 * math.pi * math.pow(Planet.radius, 2)
return str(area)  
def physical(Planet):
if Planet.moons == 1:
Planet.moons = str(Planet.moons) + " moon"
else:
Planet.moons = str(Planet.moons) + " moons"
return (Planet.name + " has a volume of " + volume(Planet) + " cubic km, a surface area of " + surface(Planet) + " sq. km, and " + Planet.moons)
def dynamic(Planet):
period = 2 * math.pi * Planet.orbital_radius * math.sqrt(Planet.orbital_radius / mu)
return (Planet.name + " has a year of approximately " + str(period // (60 * 60 * 24)) + " days")
Earth = Planet('Earth', 6371, 1, 1.496 * math.pow(10, 11))
Jupiter = Planet('Jupiter', 69911, 79, 7.786 * math.pow(10, 11))
print(physical(Earth))
print(physical(Jupiter))
print(dynamic(Earth))
print(dynamic(Jupiter))
print(Earth.collide())

我知道self.moons是由于物理函数而变成字符串的,但我该如何再次变成整数呢。它似乎不可能是整数,字符串存储为其值,这就是为什么当我尝试print(Earth.collide())时会收到错误消息ValueError: invalid literal for int() with base 10: '1 moon'

只需在空间上对字符串进行分区,并获取第一部分:

int(self.moon.partition(" ")[0])

您也可以使用str.split(),但对于"只需要拆分一次"的情况,分区要快一点。

更好的方法是不将.moons属性设置为字符串。保持它是一个整数,不需要替换它,只需要用信息格式化一个漂亮的字符串:

def physical(Planet):
if Planet.moons == 1:
moons = str(Planet.moons) + " moon"
else:
moons = str(Planet.moons) + " moons"
return (Planet.name + " has a volume of " + volume(Planet) + " cubic km, a surface area of " + surface(Planet) + " sq. km, and " + moons)

您可能需要查看格式化字符串文字或格式化字符串语法:

def physical(Planet):
moons = f"{Planet.moons} moon"
if Planet.moons != 1:
moons += 's'
return (
f"{Planet.name} has a volume of {volume(Planet)} cubic km, a surface "
f"area of {surface(Planet)} sq. km, and {moons}"
)

无论哪种方式,通过使用局部变量moons来包含格式化的卫星数值,都不会更改Planet.moons值,因此不必担心如何再次返回为整数。

我建议在def physical(Planet)中使用本地/私有变量,因为它在其他任何地方都不使用,只是一个值的格式。

def physical(Planet):
if Planet.moons == 1:
_planet_moons = str(Planet.moons) + " moon"
else:
_planet_moons = str(Planet.moons) + " moons"
return (Planet.name + " has a volume of " + volume(Planet) + " cubic km, a surface area of " + surface(Planet) + " sq. km, and " + _planet_moons)

这可以防止您来回转换值。

最新更新