2015-10-23 77 views
0

所以我想做一個程序來計算不同星球上的體重。這很令人沮喪,因爲它不能正確計算。If else statement planets

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,它會給我所有人的完全相同的數字。有人可以幫忙嗎?

+0

你可以發佈完整的代碼來測試它,或者它是一個功能完整的部分,如果它太長。 – Leb

+0

你可以發佈你的所有代碼嗎? – PolarisUser

+2

爲什麼不使用字典來將星球名稱映射到權重因子,而不是所有那些如果語句? – Barmar

回答

0

"Mercury" or "mercury" == planetName這樣的聲明不會做你想要的。

你必須給他們分開來寫像("Mercury" == planetName) or ("mercury" == planetName)

使用字典來獲得從名字的因素可能是一個很好的選擇。

1

嘗試if ("Mercury"==planetName or "mercury"==planetName) ...

等上下行。由於if ("Mecury")評估結果爲true,您的第一條陳述很可能正在執行。

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' 
+2

你的意思是'如果planetName.lower()=='mercury'?我只是想補充一點。 – saulspatz

+0

刪除了最後的評論。是的,那就是我的意思。 – froggythefrog

+0

感謝一堆它後,我放在(planetName =='水星'或planetName =='水銀'): – Austin

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

如果我可以upvote你再次爲您的編輯,我會。 :) – froggythefrog