Now that you have variables,, you’d probably like to do something with them. So let’s talk about expressions. An expression is any portion of a statement that ultimately reduces to a value. The good news is that Python expressions look similar to, and follow the same rules as, expressions in many other programming languages.

The syntax is simple and straightforward. No semicolons are required, unless you are separating two expressions (or statements) on the same line. Most if not all of the usual arithmetic and logical operators are provided, and are summarized in a table below. The rules on order of precedence are the same as in other languages (and written algebra), and parentheses change the order as you would expect. So,

in python is 11, not 16. In other words, it is the same as:

and not

This is because multiplication has a higher precedence than addition. Exponentiation is denoted by **, and as usual, these power operators take the highest precedence. Bitwise operators work the same as in C, i.e., << and >> shift bits left and right, while & and | do bitwise and and or operations, respectively.

In addition to the basic arithmetic operators, most shortcut operators work as they do in C. So for instance, if you wanted to do the following:

You can write that as:

Either way, the statement says to evaluate the expression X+5 and assign the result to X. This trick works with other operations as well; thus, if you want to multiply a variable by something and assign it to a new variable with the same name, you can use *=. (There isn’t a ++ shortcut, however.)

Python also provides for expressions that evaluate to True or False, i.e., expressions that produce a result of the bool (Boolean) type. The usual operators for making comparisons between numerical values or variables are available:

  • Order comparison: x < y; x <= y; x >= y; x > y
  • Equality, inequality: x == y; x != y

The logical operators not, and, or for Boolean expressions are available as well, for example:

In the table below, we summarize some of the more common arithmetic and logical operators provided by the Python language, including examples of their use and the results of those expressions.

Python language: examples of common arithmetic use and the results of the expressions.
Name Operator Example
Addition + 3 + 2 → 5
Subtraction - 3 - 2 → 1
Multiplication * 3 * 2 → 6
Division / 3 / 2 → 1.5/td>
Exponentiation ** 3 ** 2 → 9
Floor division (floored quotient) // 3 // 2 → 1
Modulo (remainder) % 3 % 2 → 1
Equality testing == 3 == 2 → False
Inequality testing != 3 != 2 → True
Greater than > 3 > 2 → True
Less than < 3 < 2 → False
Logical and and True and False → False
Logical or or True or False → True
 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement