Skip to content

Computer Science · Ch 5 — Getting Started with Python

Operators

5.8

Operators

An operator is a symbol that tells Python to carry out a specific mathematical or logical operation on one or more values. The values an operator acts upon are called operands.

Take this expression:

10 + num

Here the number 10 and the variable num are the two operands, while the plus sign + is the operator that combines them.

Categories of operators in Python

Python provides several families of operators, each covered in the sub-sections that follow:

  • Arithmetic operators — perform calculations such as addition, subtraction, multiplication, division, remainder, floor division and exponentiation.
  • Relational (comparison) operators — compare two values and report the relationship between them as True or False.
  • Assignment operators — store a value in a variable, or update a variable using a shorthand combining calculation and assignment.
  • Logical operators — combine or negate truth values (and, or, not).
  • Identity operators — test whether two names refer to the very same object in memory (is, is not).
  • Membership operators — test whether a value occurs inside a sequence (in, not in).

How Python compares strings

One point worth knowing before we look at relational operators: when Python compares two strings, it does so lexicographically (dictionary order), using the ASCII values of the characters. The comparison works character by character:

  • The first character of one string is compared with the first character of the other.
  • If they are the same, the second characters are compared, and so on, until a difference is found or one string ends. …