Python for Artificial Intelligence Beginner 10 minutes

Operators

Arithmetic, comparison and logical operators, and the order in which they run.

Your progress in the track0%

Arithmetic operators

The operatorMeaningExampleResult
+Addition7 + 29
-Subtraction7 - 25
*Multiplication7 * 214
/Division7 / 23.5
//Floor division7 // 23
%Remainder7 % 21
**Exponentiation7 ** 249

Comparison operators

return a Boolean value True or False:

5 == 5     # True
5 != 3     # True
3 < 2      # False
0 < 5 < 10 # True (chained comparison)

Logical operators

accuracy = 0.91
loss = 0.2
accuracy > 0.9 and loss < 0.3   # True
not (accuracy > 0.95)           # True

and andor are evaluated with short-circuiting: if the result is decided by the first operand, the second is not evaluated.

Membership and compound assignment

"ai" in "explainable ai"   # True
count = 0
count += 1                 # equivalent to count = count + 1

Operator precedence

Exponentiation first, then multiplication and division, then addition and subtraction, then comparisons, then not then and then or. When in doubt, use parentheses: (a + b) * c is clearer and safer.

Lesson terms

Operator precedence
The rules that determine the order in which operations are carried out in an expression containing more than one operation.
Floor division
The // operator, which returns the result of division rounded down.

Abstract

Python provides arithmetic operators (+ - * / // % **), comparison operators (== != < > <= >=), logical operators (and or not) and membership operators (in). Operator precedence determines which operations run first, and parentheses can be used to make the order clear.

Review questions

  1. What is the result of 7 // 2, and of 7 % 2?

    The first is 3 (floor division) and the second is 1 (remainder).

  2. What is the difference between = and ==?

    = is for assignment, and == is for comparing equality.

Sources and references

  1. Expressions: Operator precedence — Python documentation
  2. Built-in Types: Numeric Types — Python documentation

Complete the lesson