Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 5 of 25

Operators

Arithmetic operators work on numbers:

  • + add, - subtract, * multiply
  • / divide, which always gives a float: 7 / 2 is 3.5
  • // floor division, the whole-number part: 7 // 2 is 3
  • % remainder: 7 % 2 is 1
  • ** power: 2 ** 5 is 32

Python follows the usual order: brackets first, then **, then *, /, //, %, and finally + and -.

Comparison operators give True or False: == equal, != not equal, <, >, <=, >=. Logical operators combine them: and needs both sides true, or needs at least one, and not flips the result.

marks = 72
print(marks >= 40 and marks < 75)

Key takeaways

  • / always gives a float, // gives the whole-number part and % gives the remainder: 7 / 2 is 3.5, 7 // 2 is 3 and 7 % 2 is 1.
  • ** is the power operator: 2 ** 5 is 32.
  • Multiplication and division happen before addition and subtraction, and brackets come first.
  • Comparisons give True or False, and and, or and not combine them.

Common mistakes

  • Dividing by zero, for example when an average is worked out from an empty list. Read the ZeroDivisionError guide.
  • Using ^ for power. In Python ^ is a different operator, so write **.
  • Forgetting that / gives a decimal even when the answer is whole: 10 / 5 is 2.0.

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.