Wil*_*ire 1 python windows string if-statement boolean
我有一个程序可以测试行星与太阳的距离.唯一的问题是,无论我说什么答案,它始终显示为正确.这是我的代码的链接: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()
Run Code Online (Sandbox Code Playgroud)
问题是你有:
if mercury or mercury2 in ans:
Run Code Online (Sandbox Code Playgroud)
这个if语句将是True,如果mercury计算结果为True(它总是这样),或者mercury2 in ans是True.
mercury是一个非空字符串(mercury = "57.9"),将评估为True.例如,尝试bool("57.9")查看Python始终计算True非空字符串.如果字符串为空,那么它将是False.
因此,无论用户回答什么,您的代码总是会说它是正确的.这是你可以写的:
if mercury in ans or mercury2 in ans:
Run Code Online (Sandbox Code Playgroud)
但写起来可能更好(参见下面评论中的讨论):
if ans in [mercury, mercury2]:
Run Code Online (Sandbox Code Playgroud)
你有这个:
if mercury or mercury2 in ans:
Run Code Online (Sandbox Code Playgroud)
而不是这个:
if ans in (mercury, mercury2):
Run Code Online (Sandbox Code Playgroud)
但是你有一个更深层次的问题.像这样的代码
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()
Run Code Online (Sandbox Code Playgroud)
最终将导致堆栈溢出.这是因为你正在调用函数,但永远不会从它们返回!
您应该重新构造代码以使用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")
Run Code Online (Sandbox Code Playgroud)
您可以通过将行星数据存储在a中来进一步发展 list