首页 > 解决方案 > Python if 语句总是返回 false,即使输入为 true

问题描述

所以我正在编写一个程序(一种“自定义 if 语句”)来检查您的输入是真还是假。这是我现在拥有的脚本:

v=line[3:] # Remove "if " from the line, so you only have the question and the consequence
i=v.split(': ') # Make a list with the first item being the question and the second item being the consequence.
for r in i:
    if r==i[1]: # Check which item in the list is the question and which is the consequence
        c=r
        question=i[0]
        consequences=c.split(' | ')
    for x in consequences:
        self.consequences+=f'\n{x}' # Create a variable with all of the consequences, each in one line
    Answer=False # reate the Answer variable with the default value False
    def checkVal(question):
        global Answer
        if question:
            b=open('if.BaRT','w+')
            b.write(self.consequences)
            b.close()
            self.run('if.BaRT')
            os.remove('if.BaRT')
        else:
            pass # Check if the question is true or false
    if Answer==True:
        print("True!")
    else:
        print("False!") # Finally check if the question is true or not and if it is, print "True!" and if it's not, print "False!"

我希望这可以工作,但是当我输入一些真实的东西时,例如:__name__=="__main__",所以我的输入看起来像这样:

if __name__=="__main__": print("Hello!")

这是输出:

False!

我该如何解决这个问题,以便准确打印?

标签: pythonif-statement

解决方案


编辑:添加的后果

我已经用 eval 替换了你的 exec 以摆脱你的全局变量(仍然不是很好的编码实践,但如果这是你需要的......)。此外,不需要 for。

PS:变量 i、v 和 c 应该有更好的名称。

line='if __name__=="__main__": print("Hello!")'
v=line[3:] # Remove "if " from the line, so you only have the question and the consequence
i=v.split(': ') # Make a list with the first item being the question and the second item being the consequence.

c=i[1]
question=i[0]
consequences=c.split(' | ')

_consequences=''
for x in consequences:
   _consequences+=f'\n{x}' 
Answer=eval(f"{question}") # Check if the question is true or false

if Answer==True:
  exec(  _consequences)
  print("True!")
else:
  print("False!") # Finally check if the question is true or not and if it is, print "True!" and if it's not, print "False!"

推荐阅读