Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Operators

An operator is a symbol that works on values: + adds, == compares, and combines. You have met several already. This topic collects them in groups and explains the order in which Python applies them when an expression has more than one.

Arithmetic and assignment

OperatorMeaningExampleResult
+ - *add, subtract, multiply7 * 321
/divide7 / 23.5
//divide and round down7 // 23
%remainder7 % 21
**power2 ** 532

Every arithmetic operator has an assignment form that changes a variable in place: x += 3 is x = x + 3, and likewise -=, *=, /=, //=, %= and **=.

x = 10
x += 5
x *= 2
x //= 4
x **= 2
print(x)
Output
49

Comparison and logic

==, !=, <, >, <= and >= compare two values and give a boolean; and, or and not combine booleans. The Booleans topic explains them in detail.

Membership and identity

in and not in check whether a value is part of a collection or of a string. is and is not check whether two names refer to the same object, which is different from having equal values:

fruits = ["apple", "mango"]
print("mango" in fruits, "kiwi" not in fruits)
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)
value = None
print(value is None)
Output
True True
True False True
True

a and b are equal lists but two separate objects; c is another name for the very same list as a. Use == to compare values, and keep is for checking None.

Bitwise operators

&, |, ^, ~, << and >> work on the binary digits of whole numbers. They are used for flags and low-level data: 6 & 3 is 2, 6 | 3 is 7, and 1 << 4 is 16. You will rarely need them while learning.

Order of precedence

When an expression has several operators, Python applies them in a fixed order: ** first, then *, /, // and %, then + and -, then comparisons, then not, and and or. Brackets always come first, so use them whenever the order is not obvious:

print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)
print(-3 ** 2, (-3) ** 2)
Output
14
20
512
-9 9

** is the one operator that groups from the right: 2 ** 3 ** 2 is 2 ** 9. It also binds tighter than a minus sign in front, so -3 ** 2 is -(3 ** 2).

Practice exercises

  1. Start with n = 7 and use assignment operators to make it 7 times larger, then subtract 9, then halve it with //.
  2. Check with in whether the letter "y" is in "Python" and in "Java".
  3. Work out 100 - 5 * 3 ** 2 by hand, then check it in the interpreter.
  4. Create two equal lists and show that == is True but is is False.