1

基本上我对 python 很陌生,所以我决定做一个简单的计算器,我已经完成了计算器的编码,一切正常,我很高兴,但是我想要一个 if-else 语句来看看他们是否愿意继续另一个计算。所以这是我的代码的顶部和我的代码的底部,我想知道如何获取它,以便在代码的“else”部分之后,它只运行其余的代码。

import os
done = ("")
if done == True:
    os._exit(0)
else:
    print ("---CALCULATOR---")

...

done = str(input("Would you like to do another calculation? (Y/N) "))
if done == "N" or "n":
    done = True
if done == "Y" or "y":
    done = False

任何帮助,将不胜感激。

4

2 回答 2

2

if done == "N" or "n":

上述条件检查是否done == "N""n"。这将始终计算为,True因为在 Python 中,非空字符串的计算结果为 boolean True

正如评论中所建议的,您应该使用 while 循环让程序继续执行,直到用户输入“N”或“n”。

import os
finished = False

while not finished:
    print ("---CALCULATOR---")
    ...

    done = str(input("Would you like to do another calculation? (Y/N) "))
    if done == "N" or done == "n":
        finished = True
于 2013-11-13T18:28:56.717 回答
2

你会想要这样的东西...

import os
done = False

while not done:
    print ("---CALCULATOR---")
    ...

    # be careful with the following lines, they won't actually do what you expect
    done = str(input("Would you like to do another calculation? (Y/N) "))
    if done == "N" or "n":
        done = True
    if done == "Y" or "y":
        done = False
于 2013-11-13T18:23:42.277 回答