如果有别的说法行星

2024-03-29 13:30:49 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想做一个程序来计算不同行星的重量。这是令人沮丧的,因为它无法正确计算。在

if ("Mercury" or "mercury" == planetName):                        
    weight = weightObject * mercury
elif ("Venus" or "VEnus" == planetName):                       
    weight = weightObject * venus                 
elif ("Earth's Moon" or "Earths Moon" == planetName):                     
     weight = weightObject * earthsmoon
elif ("Mars" or "MArs" or "MARS" == planetName):                       
    weight = weightObject * mars
elif ("Jupiter" or "JUpiter" == planetName):                       
    weight = weightObject * jupiter
elif ("Saturn" or "saturn" == planetName):                       
    weight = weightObject * saturn
elif ("uranus" or "Uranus" == planetName):
    weight = weightObject * uranus
elif ("neptune" or "Neptune" == planetName):
    weight = weightObject * neptune
elif ("pluto" or "Pluto" == planetName):
     weight = weightObject * pluto
else:
    weight = -1

#To print out the planet and weight and make sure its a planet and non   negative number
#It will not calculate a negative weight or different planet than listed

if (weightObject > 0):
print("The weight of the object on",planetName,"is {0:,.2f}".format(weight))
else:
    print("Error: Planet name not found or number was negative. Please try      again.")

如果我为每个行星输入20.5,那么所有行星的数字都是完全相同的。有人能帮忙吗?在


Tags: orandif行星printweightelifmercury
3条回答
if ("Mercury" or "mercury" == planetName):                        
    weight = weightObject * mercury

应该是

^{pr2}$

或者更简洁

^{3}$

甚至是

if planetName.lower() == 'mercury'

尝试if ("Mercury"==planetName or "mercury"==planetName) ...

等等。您的第一个语句很可能是由于if ("Mecury")的计算结果为true而执行的。在

尝试:

if(planetName in ["Mercury", "mercury"])

或者更简单:

^{pr2}$

另外,打开python解释器并开始键入以下内容是一个好主意:

^{3}$

了解python中哪些计算结果为true,哪些计算结果为false。它会让你的生活更轻松

或者另一个很酷的把戏,把你乘以的值放到字典里。在

weights = {"mercury": mercury, "venus": venus, "Earth's Moon": earthsmoon, "Earths Moon": earthsmoon .... etc.}
try:
    weight = weights[planetName.lower()] * weightObject
except KeyError:
    weight = -1

if weight > 0:
    .......

相关问题 更多 >