-3

I need the explanation of this syntax , does this mean that (+4) is the same as (4) ? I have tried many other operands and it completely works as if I disregarded the plus sign before the number .

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253

5 Answers5

4

Would you be confused by

4 > -4

The only difference between that and

4 > +4 

is a different unary operator

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
3

The + in +4 is the unary plus operator:

The unary + (plus) operator yields its numeric argument unchanged.

So yes, because 4 is a number (an int), +4 means just the same thing as 4, as the operator returns the number unchanged.

The operator exists as a counterpart to the - unary minus operator:

4 > -4

Custom classes could override it using the __pos__() method, making it possible to return custom results.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

(In addition to the points pointed out by the other answers ...)

The comparison operations in Python have lower precedence than the positive unary operator (+operand):

Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation.

This means that the unary plus operator applied to its operand will be evaluated prior to the comparison operator, and +4 will result in simply just 4 prior the unary comparison operation even starting.

4 < +4
4 < (+4)
4 < 4
dfrib
  • 70,367
  • 12
  • 127
  • 192
0

Yes, they're effectively the same. The unary + operator in +4 is applied to the 4 and 4 is the result.

B. Eckles
  • 1,626
  • 2
  • 15
  • 27
0

To check if your variables are the same type them into your interpreter with the == operator between them. If they are the same, this will return True.

>>> 4 == +4
True

This may seem daft or obvious in this case, but when working with more complex variables it can be more useful.

maze88
  • 850
  • 2
  • 9
  • 15