Operators

Operators in Python are all about manipulating data. The most common operator types are:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators

Arithmetic operators

Arithmetic operators are used to carry out common mathematical operations.

Arithmetic operatorMeaning
a + bAdds the value of b to a
a – bSubtracts the value of b from a
a * bMultiplies a by b
a / bDivides a by b
a ** bRaises a to the power of b
a % bDivides a by b and returns the remainder
a // bDivides a by b and rounds down
Arithmetic operators and their meaning

Assignment Operators

Assignment operators are a shortcut that combine an arithmetic operator and then assign the outcome of that equation to a variable. For example:

total_number_of_days += days_this_week

Is the same as typing:

total_number_of_days = total_number_of_days + days_this_week
Assignment operatorsMeaning
a += ba = a + b
a -= ba = a -b
a *= ba = a * b
a /= ba = a/ b
a **= ba = a ** b
a //= ba = a // b
Assignment operators and their meaning

Comparison Operators

Comparison Operators compare two variables or statements and return a Boolean True or False.

Comparison OperatorsMeaning
a == bTrue if a is equal to b
a != bTrue if a is not equal to b
a < bTrue if a is less than b
a > bTrue if a is greater than b
a <= bTrue if a is less than or equal to b
a >= bTrue if a is greater than or equal to b
Comparison operators and their meaning

Logical Operators

Logical Operators are used to combine statements and return a Boolean True or False based on the result.

Logical operatorMeaning
a or bTrue if either a or b is True
a and bTrue only if both a and b are True
not aTrue if a is False
Logical operators and their meaing


Precedence

Precedence determines the order in which operations are carried out. An operation with a higher precedence will be calculated before a lower one.

Highest PrecedenceOperatorSymbol
Parentheses()
Exponential**
Multiplication, division, modulo, and floor division*, /, %, //
Addition and subtraction+, –
Comparison operators<, >, <=, >=
Equality operators==, !=
Assignment operators=, +=, -=, *=, /=, %=, //=, **=
Lowest precedenceLogical operatorsor, and, not
Order of operator precedence

If in any doubt, wrap the separate parts in brackets so that each operation is unaffected by the others.

total = ((a + b) – (x * y)) / z
Report a Glow concern
Cookie policy  Privacy policy

Glow Blogs uses cookies to enhance your experience on our service. By using this service or closing this message you consent to our use of those cookies. Please read our Cookie Policy.