Tuesday 9 April 2019

Python Operators

Python Operators

Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:
OperatorNameExampleTry it
+Additionx + yTry it »
-Subtractionx - yTry it »
*Multiplicationx * yTry it »
/Divisionx / yTry it »
%Modulusx % yTry it »
**Exponentiationx ** y
//Floor divisionx // y

Python Assignment Operators

Assignment operators are used to assign values to variables:
OperatorExampleSame AsTry it
=x = 5x = 5Try it »
+=x += 3x = x + 3Try it »
-=x -= 3x = x - 3Try it »
*=x *= 3x = x * 3Try it »
/=x /= 3x = x / 3Try it »
%=x %= 3x = x % 3Try it »
//=x //= 3x = x // 3Try it »
**=x **= 3x = x ** 3Try it »
&=x &= 3x = x & 3Try it »
|=x |= 3x = x | 3Try it »
^=x ^= 3x = x ^ 3Try it »
>>=x >>= 3x = x >> 3Try it »
<<=x <<= 3x = x << 3Try it »


Python Comparison Operators

Comparison operators are used to compare two values:
OperatorNameExampleTry it
==Equalx == yTry it »
!=Not equalx != yTry it »
>Greater thanx > yTry it »
<Less thanx < yTry it »
>=Greater than or equal tox >= yTry it »
<=Less than or equal tox <= yTry it »

Python Logical Operators

Logical operators are used to combine conditional statements:
OperatorDescriptionExampleTry it
and Returns True if both statements are truex < 5 and  x < 10Try it »
orReturns True if one of the statements is truex < 5 or x < 4Try it »
notReverse the result, returns False if the result is truenot(x < 5 and x < 10)Try it »

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:
OperatorDescriptionExampleTry it
is Returns true if both variables are the same objectx is yTry it »
is notReturns true if both variables are not the same objectx is not yTry it »

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:
OperatorDescriptionExampleTry it
in Returns True if a sequence with the specified value is present in the objectx in yTry it »
not inReturns True if a sequence with the specified value is not present in the objectx not in yTry it »

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:
OperatorNameDescription
ANDSets each bit to 1 if both bits are 1
|ORSets each bit to 1 if one of two bits is 1
 ^XORSets each bit to 1 if only one of two bits is 1
NOTInverts all the bits
<<Zero fill left shiftShift left by pushing zeros in from the right and let the leftmost bits fall off
>>Signed right shiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

No comments:

Post a Comment