我有一些python类型的代码,我想知道为什么python eval方法返回false。 [英] I have some python type code and am wondering why the python eval method return false.

查看:217
本文介绍了我有一些python类型的代码,我想知道为什么python eval方法返回false。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手以及eval如何工作,所以任何帮助都会受到赞赏。



我得到了一个具有以下值的变量表达式检查某些字符串。



这是表达式:



I'm kind of new to python and how eval works, so any help is appreciated.

I was given an expression of variables that have the following values to check certain strings.

Here is the expression:

eval(("PRES" == "PRES" + "PRES"=="PRES")==1)







现在,也许我误解了表达式是如何工作的,从语法看起来似乎是一个AND,看看两者是否都评估为真,

但我得到的是假的回报。



是否有一些特殊情况为+或== 1?



有人能说清楚表达/做什么吗?




Now, perhaps I am misunderstanding how the expression is working, buut from the syntax it seems like an AND to see if both evaluate to true,
but i get a false in return.

Is there some special case for the + or the == 1?

Can anyone clarify what the expression is saying/doing?

推荐答案

该代码甚至无效,因为 eval 只接受一个字符串;所以,如果你想让它发挥作用,你应该在表达式周围加上引号。除此之外,如果你的表达式是这样的硬编码,你不需要eval。



关于你的表达式,实际上它的计算结果为:

That code is not even valid, because eval only accepts a string; so if you would want to make it work, you should put quotes around your expression. Aside from that, if your expression is a hard-coded one like this, you don't need eval.

About your expression, actually it evaluates to this:
("PRES" == ("PRES" + "PRES") == "PRES") == 1

("PRES" == "PRESPRES" == "PRES") == 1

False == 1

False



这就是它的作用/>


如何解决?使用而不是 + 。但是不要使用 + ,因为即使你使用括号来确保它是(PRES==PRES)+ (PRES==PRES)然后它将是2.



所以,为了使它真实,你的表达应该看起来像这样:


That's what it does.

How to fix it? Use use an and instead of a +. But don't use +, because even if you would use parentheses to make sure it would be ("PRES" == "PRES") + ("PRES" == "PRES") then it would be 2.

So, to make it true, your expression should look like this:

"PRES" == "PRES" and "PRES" == "PRES"



== 1 不是必需的;因为如果上面的表达式也是True,它仍然是True。


==1 is not necessary; because it would still be True if the above expression is also True.


这篇关于我有一些python类型的代码,我想知道为什么python eval方法返回false。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆