繁体   English   中英

Python if 语句总是返回 false,即使输入为 true

[英]Python if statement always returns false, even though input is 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!

我该如何解决这个问题才能准确打印出来?

编辑:添加的后果

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM