Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

=+ Python operator is syntactically correct

I accidentally wrote:

total_acc =+ accuracy

instead of:

total_acc += accuracy

I searched the net and could not find anything. So what happened, why does Python think I mean what I am typing?

Computers trust us too much. :)

like image 486
gsamaras Avatar asked Feb 05 '16 19:02

gsamaras


People also ask

What is a Python operator?

In Python, operators are special symbols that designate that some sort of computation should be performed. The values that an operator acts on are called operands. Here is an example: >>> >>> a = 10 >>> b = 20 >>> a + b 30. In this case, the + operator adds the operands a and b together.

What type of operator is operator Python?

Python operator is a symbol that performs an operation on one or more operands. An operand is a variable or a value on which we perform the operation. Python Operator falls into 7 categories: Python Arithmetic Operator.


2 Answers

If you are interested in catching this type of errors early, you can do that with static code analysis. For example, flake8:

$ cat test.py
total_acc = 0
accuracy = 10

total_acc =+ accuracy
$ flake8 test.py
test.py:4:12: E225 missing whitespace around operator

In this case, it is complaining about the extra space after the +, thinking that you actually meant total_acc = +accuracy. This would have helped you to discover the problem earlier.

FYI, pylint would catch that too.

like image 121
alecxe Avatar answered Sep 28 '22 00:09

alecxe


This is the same as if you were to do like total_acc = -accuracy, except positive instead of negative. It basically is the same as total_acc = accuracy though, as adding a + before a value does not change it.

This is called an unary operator as there is only one argument (ex: +a) instead of two (ex: a+b).

This link explains it a little more.

like image 41
John Howard Avatar answered Sep 28 '22 00:09

John Howard