inputing an logical expression as string and evaluating, i'm getting proper output
str1 = "(1|0)&(1|1&(0|1))"
print eval(str1)
o/p: 1
But the same way if i'm including not operator as ~, the output goes wrong.
str1 = "(~0|~1)&(~1|0)"
print eval(str1)
o/p: -2
Is there any other way of representing not operator here to get proper answer.
These are not logical expressions but bitwise expressions. That is the reason why ~0 == -1. Instead you can look for a parser that parses these expressions the way you want. A quick google search showed up this stackoverflow question.
Sympy seems to implement a similar thing: sympy logic
The logic module for SymPy allows to form and manipulate logic expressions using symbolic and boolean values
&, | and ~ are bitwise operators.
For logic operators use and, or and not.
If your intention is to do logical operations, prefer to use the appropriate boolean values:
True / False
str1 = "(not 0|not 1) and (not 1|0)"
print eval(str1)
In python NOT is not
Ref : https://docs.python.org/2/library/stdtypes.html
Related
Just to check, I couldn't find anything about ~, so I want to make sure it's the same.
Also, can you use ! in python like in C++?
It seems that these two codes give the same output:
bool(~0)
bool(not 0)
This is how it is in Python.
'~' is a bitwise operator
whereas 'not' is a logical opeartor
You should read Python 3.10 documentation at Unary arithmetic and bitwise operations.
The ~ operator does a simple job:
Inverts the bits
I want to convert this string into a result n for the output to be 11.
a = "1+5*6/3"
print (a)
The eval() built-in function can evaluate a Python expression including any arithmetic expression. But note the eval() function is a security concern because it can evaluate any arbitrary Python expression or statement so should be used only if the input to evaluate is controlled and trusted user input. There are examples to why eval() is dangerous in this question.
a = "1+5*6/3"
result = eval(a)
print(result)
Output:
11.0
Using ast module as an alternative to eval()
A safe alternative to eval() is using ast.literal_eval. Recent Python 3 versions disallows passing simple strings to ast.literal_eval() as an argument. Now must parse the string to buld an Abstract Syntax Tree (AST) then evaluate it against a grammar. This related answer provides an example to evaluate simple arithmetic expressions safely.
You can directly use the python eval function.
a = eval("1+5*6/3")
print(a)
I'm studying operators in Python and came across multiple concepts that decide order of evaluation when there are multiple operators in an expression.
I understand the concept of Operator precedence, and came across the operator precedence table in Python docs. There were a few things that confused me there,
Why are assignment and augmented-assignment operators not included in the list?
What really counts as an operator in Python? (And is there any difference between operator and a keyword).
The later question stems from what the categorization of operator that I've read at various places on the internet, they categorize operators in the following categories
Arithmetic Operators
Comparison Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
But when I saw keywords like lambda, if-else in the operator precedence table in the Python documentation, it confused me. Moreover the operator mapping table in documentation for operator module includes keywords like del which are neither part of usual categorization on the internet and the precedence table in Python docs.
My final question is "is there any grouping that can be done about the
categories of operators and their behavior (precedence, chaining, associativity, etc) in Python? Or should I be studying every operator and its behavior independently?"
Why are assignment and augmented-assignment operators not included in the list?
Because they're not true operators. We sometimes call them operators for convenience, but they cannot form expressions and therefore do not have precedence relative to real operators.
What really counts as an operator in Python? (And is there any difference between operator and a keyword).
According to the doc on operators, it seems to be any punctuation that can form an expression. For simplicity, I prefer to define an operator as any punctuation or keyword that can form an expression.
But when I saw keywords like lambda, if-else in the operator precedence table in the Python documentation, it confused me.
Those are keywords that can form expressions, therefore they must have operator precedence. Note that if-else can be an expression or a block statement, depending on the syntax:
# Expression
a if condition else b
# Statement
if condition:
pass
else:
pass
Moreover the operator mapping table in documentation for operator module includes keywords like del which are neither part of usual categorization on the internet and the precedence table in Python docs.
del is not an operator, because it's used only to get a side-effect. However, it can potentially modify an object in place, so it makes sense to include a function in the operator library that does the same thing. The other use for del is to remove a variable, which is something a function can't do.
My final question is "is there any grouping that can be done about the
categories of operators and their behavior (precedence, chaining, associativity, etc) in Python? Or should I be studying every operator and its behavior independently?"
Operators can always be combined to form larger expressions, so they must have precedence and associativity to define the meaning of a non-trivial expression. Non-operator syntax usually forms either a statement or a group of statements.
I get boolean expression like below :
string = '!True && !(True || False || True)'
I know eval('1+2') returns 3. But when I am executing eval(string) it is throwing me error as in invalid syntax.
Is there any other way I can execute the above expression?
None of !, && and || are valid Python operators; eval() can only handle valid Python expressions.
You'd have to replace those expressions with valid Python versions; presumably ! is not, && is and, and || is or, so you could just replace those with the Python versions:
eval(string.replace('&&', 'and').replace('||', 'or').replace('!', 'not '))
Note the space after not because Python requires this.
The better approach would be to not use the wrong spelling for those operators (they look like Java or JavaScript or C).
If you want to parse boolean logic (in contrast to control flow) take a look at this stackoverflow post. It mentions pyparsing
The pyparsing module is an alternative approach to creating and executing simple grammars
and sympy.
The logic module for SymPy allows to form and manipulate logic expressions using symbolic and boolean value.
There also seems to be a parser implemented with pyparsing.
Of course you could also write a parser yourself.
I've got the IF statement;
if contactstring == "['Practice Address Not Available']" | contactstring == "['']":
I'm not sure what is going wrong(possibly the " ' "s?) but I keep getting the error mentioned in the title.
I've looked in other questions for answers but all of them seem to be about using mathematical operates on strings which is not the case here. I know this question is kind of lazy but I've been coding all day and I'm exhausted, I just want to get this over with quickly.(Python newb)
| is a bitwise or operator in Python, and has precedence so that Python parses this as:
if contactstring == (""['Practice Address Not Available']"" | contactstring) == "['']":
Which generates the error you see.
It seems what you want is a logical or operator, which is spelled 'or' in Python:
if contactstring == ""['Practice Address Not Available']"" or contactstring == "['']":
Will do what you expect. However, since you're comparing the same variable against a range of values, this is even better:
if contactstring in ("['Practice Address Not Available']", ['']):
The | is a bitwise operator which doesn't work on strings...
Using or (a boolean logic operator) will yield better results.
The problem here is the bitwise-or operator |. In a Boolean context that would normally work OK, but | has higher precedence than == so Python is trying to evaluate "['Practice Address Not Available']" | contactstring first. Both of those operands are strings, and you can't bitwise-or two strings. Using the more correct or avoids this problem since it's lower precedence than ==.