你有這樣的:
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
有150行代碼,可以喲你縮小了問題的範圍,只是發佈相關的代碼? (這個過程也會加深你對代碼的理解) – Levon 2012-08-14 16:14:53
[SSCCE](http://robzu.com/sscce-short-self-contained-correct-compilable-example) – RobB 2012-08-14 16:15:33