【问题标题】:Issue with simple python program简单的python程序的问题
【发布时间】:2012-08-10 23:49:13
【问题描述】:

我有一个程序可以问我行星离太阳有多远。唯一的问题是,无论我给出什么答案,它总是显示为正确的。这是我的代码的链接: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()

【问题讨论】:

  • 有 150 行代码,你能缩小问题范围,把相关的代码贴在这里吗? (这个过程也会加深你对代码的理解)

标签: python windows string if-statement boolean


【解决方案1】:

问题是你有:

if mercury or mercury2 in ans:

如果mercury 的计算结果为True(它总是如此)或mercury2 in ansTrue,则此if 语句将为True

mercury 是一个非空字符串 (mercury = "57.9"),其计算结果为 True。例如,尝试 bool("57.9") 以查看 Python 总是为非空字符串计算 True。如果字符串为空,则为False

因此,无论用户回答什么,您的代码都会始终说它是正确的。以下是你可以写的:

if mercury in ans or mercury2 in ans:

但写起来可能更好(参见下面 cmets 中的讨论):

if ans in [mercury, mercury2]:

【讨论】:

  • 或者可能是if ans in [mercury, mercury2]
  • @Deestan:这也可以,但这确实意味着用户必须只回答一个数字。如果他们回答"57900000 (roughly)",那就错了。
  • 嗯,是的,但另一种选择有误报。 “34539485934557.99”将被认为是正确的。
  • @Deestan:好点,那更糟。我会更新我的答案。
  • 谢谢,我的代码现在运行得更好了!现在回到记忆 ESRT...
【解决方案2】:

你有这个:

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()

最终会导致 stackoverflow。这是因为您正在调用函数,但从未从它们返回!

您应该重组代码以使用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 中来更进一步

【讨论】:

  • +1 表示非常重要的观察永远不会从Mercury()返回
【解决方案3】:

问题在于您的 if 语句条件。

例子:

if ans == venus or venus2:

这应该是:

if ans == venus or ans == venus2:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2014-05-12
    • 2012-04-12
    • 2022-01-17
    • 2021-10-28
    相关资源
    最近更新 更多