如果是其他声明行星

时间:2015-10-23 00:02:14

标签: 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,它会为我提供完全相同的数字。有人可以帮忙吗?

4 个答案:

答案 0 :(得分:4)

if ("Mercury" or "mercury" == planetName):                        
    weight = weightObject * mercury

应该是

if planetName == 'Mercury' or planetName == 'mercury'                        
    weight = weightObject * mercury

或更简洁

if planetName in ("Mercury", "mercury"):                        
    weight = weightObject * mercury

甚至

if planetName.lower() == 'mercury'

答案 1 :(得分:1)

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

依此类推。由于if ("Mecury")评估为true,您的第一个语句很可能正在执行。

答案 2 :(得分:1)

尝试:

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

或更简单:

planetName.lower() == "mercury"

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

bool("Mercury")
"Mercury" == "mercury"
"Mercury" and "mercury" == "Mercury"
"Mercury" or "mercury" == "Mercury"
bool(None)
bool(True)
bool(False)
bool([])
bool({})
bool([1])
bool({"a":"a"})

了解python中的计算结果是什么,以及什么计算结果为false。它会让你的生活更轻松:D

或者另一个很酷的技巧是将值乘以字典。

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:
    .......

答案 3 :(得分:0)

"Mercury" or "mercury" == planetName之类的语句将无法满足您的需求。

您必须像("Mercury" == planetName) or ("mercury" == planetName)

一样单独编写

使用字典从名称中获取因子可能是一个不错的选择。