简单python程序的问题

2024-04-23 16:52:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序来测试行星离太阳有多远。唯一的问题是,不管我给出什么答案,结果总是正确的。下面是我的代码链接: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()

Tags: 答案代码程序comhttp链接def行星
3条回答

问题在于if语句的条件。你知道吗

示例:

if ans == venus or venus2:

这应该是:

if ans == venus or ans == venus2:

问题是你有:

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:

但最好是这样写(见下面评论中的讨论):

if ans in [mercury, mercury2]:

你有这个:

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

最终会导致堆栈溢出。这是因为您正在调用函数,但从未从函数返回!

您应该重新构造代码以使用^{}循环

您还应该考虑从程序中删除一些重复项

你可以用这样的函数

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

相关问题 更多 >