2012-08-14 43 views
1

我有一個程序來問我行星離太陽有多遠。唯一的問題是,無論我怎麼回答,總是顯示正確。下面是我的代碼的鏈接:http://pastebin.com/MimECyjm簡單的Python程序問題

如果可能的話,我想一個更簡單的答案,因爲我不是蟒蛇是精通尚未

代碼的問題:

mercury = "57.9" 
mercury2 = "57900000" 

def Mercury(): 
    ans = raw_input("How far is Mercury from the sun? ") 
    if mercury or mercury2 in ans: 
     print "Correct!" 
     time.sleep(.5) 
     os.system("cls") 
     main() 
    else: 
     print "Incorrect!" 
     Mercury() 
+2

有150行代碼,可以喲你縮小了問題的範圍,只是發佈相關的代碼? (這個過程也會加深你對代碼的理解) – Levon 2012-08-14 16:14:53

+1

[SSCCE](http://robzu.com/sscce-short-self-contained-correct-compilable-example) – RobB 2012-08-14 16:15:33

回答

6

的問題您有:

if mercury or mercury2 in ans: 

這個if語句將True如果mercury評估爲True(它總是這樣)或mercury2 in ansTrue

mercury是一個非空字符串(mercury = "57.9"),它將評估爲True。例如,嘗試bool("57.9")以查看Python總是爲非空字符串計算True。如果字符串是空的,那麼它將是False

所以不管用戶回答什麼,你的代碼都會說它是正確的。這裏是你可以寫什麼:

if mercury in ans or mercury2 in ans: 

,但它可能會更好寫(見下面的註釋討論):

if ans in [mercury, mercury2]: 
+4

或者如果在[汞,汞2 ]' – Deestan 2012-08-14 16:18:55

+0

@Deestan:這也可以工作,但這確實意味着用戶只能用一個數字來回答。如果他們回答「57900000(大致)」,那麼這將是錯誤的。 – 2012-08-14 16:21:14

+1

好的,但另一種選擇有誤報。 「34539485934557.99」將被接受爲正確的。 – Deestan 2012-08-14 16:23:04

3

問題是與你的if語句的條件。

例子:

if ans == venus or venus2: 

這應該是:

if ans == venus or ans == venus2: 
6

你有這樣的:

if mercury or mercury2 in ans: 

,而不是這樣的:

if ans in (mercury, mercury2): 

但是,您有更深的問題。這樣

def Mercury(): 
    ans = raw_input("How far is Mercury from the sun? ") 
    if mercury or mercury2 in ans: 
     print "Correct!" 
     time.sleep(.5) 
     os.system("cls") 
     main() 
    else: 
     print "Incorrect!" 
     Mercury() 

代碼最終會導致一個計算器。這是因爲你正在調用函數,但從未返回

你應該重組代碼中使用while循環

你也應該考慮從程序去除一些重複的

例如,你可以使用這樣的函數

def main(): 
    while True:  
     print "Planetary Distance from the Sun" 
     time.sleep(.5) 
     rand = random.randint(1,1) 
     if rand==1: 
      ask_planet_distance("Mercury", mercury, mercury2) 
     elif rand==2: 
      ask_planet_distance("Venus", venus, venus2) 
     ... 


def ask_planet_distance(planet_name, distance1, distance2): 
    while True: 
     ans = raw_input("How far is {} from the sun? ".format(planet_name)) 
     if ans in (distance1, distance2): 
      break 
     else: 
      print "Incorrect!" 
    print "Correct!" 
    time.sleep(.5) 
    os.system("cls") 

你可以進一步通過將行星數據存儲在list

+0

+1對於非常重要的觀察,永遠不會從'Mercury()返回' – chepner 2012-08-14 16:29:52