即使输入为true,Python if语句也始终返回false

时间:2020-10-17 19:53:46

标签: python if-statement

因此,我正在编写一个程序(一种“自定义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!

如何解决此问题,以便准确打印?

1 个答案:

答案 0 :(得分:1)

编辑:添加了后果

我已经用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!"