python - 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!
我该如何解决这个问题,以便准确打印?
解决方案
编辑:添加的后果
我已经用 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!"
推荐阅读
- autodesk-forge - Dashboard.js Autodesk Forge
- java - 从 Eclipse 代码覆盖范围中排除特定文件/包
- nested - 具有嵌套因子的线性混合效应模型(完全嵌套设计)
- azure - Get-AzVM 在 Azure 上返回空列表
- lucene.net - Lucene.net 可以从压缩目录中搜索吗
- angular - angular11 mat-datetimepicker with moment-datetimer-adapter 不使用时间戳
- ios - 重新获取苹果凭据(Apple 使用 Expo 登录)
- python - Python,使用超过 20 次 mock.patch.object() 和太多静态嵌套块错误
- python - bash:/home/khawar/.local/bin/pip3:/home/khawar/anaconda3/envs/AAAIFace/bin/python:错误的解释器:没有这样的文件或目录
- r - 根据样本(行)中的存在选择列 R