LESSON 5 / 5 · 8 MIN
Basic Operators
LET'S MAKE IT CLICK
Combine your values
Operators combine or compare values. An expression such as 7 + 2 evaluates to a result you can assign or print.
The first operand.
Choose the operation.
Combine the two operands.
An operator connects values to produce a result.
Move through one idea at a time. Watch, experiment, and check your understanding along the way.
Start with arithmetic
Find the sum.
Find the product.
True division produces a float here.
Different operators answer different questions about the same two values.
Use + for addition, - for subtraction, and * for multiplication. The / operator performs true division: with integers, its result is a float, so 8 / 2 produces 4.0.
See the Python code
print(7 + 2) # 9
print(7 * 2) # 14
print(7 / 2) # 3.5Whole quotients and remainders
Start with the exact quotient here.
Move toward negative infinity.
Because -7 = (-4 × 2) + 1.
Floor division rounds down. The remainder keeps the integer division relationship true.
With integer operands, // gives the quotient rounded down, and % gives the remainder. For example, 7 // 2 is 3 and 7 % 2 is 1.
Rounded down means toward negative infinity: -7 // 2 is -4, not -3. Python keeps the relationship a = (a // b) * b + (a % b) for integer operands with a nonzero divisor.
YOUR TURN TO EXPLORE
Change an operator. Inspect the result.
Choose two integers and an operation. Try division by zero or a negative input and watch what Python would display.
No assignments yet.
OUTPUT
No output yet.
Predict the result, then take the first step.
Compare values
Ask whether the values are equal.
The comparison is satisfied.
A comparison returns a boolean.
Use == to compare. A single = assigns a value to a name.
== checks equality; > checks whether the left value is greater. Comparisons produce a boolean: True or False. Remember that = assigns and == compares.
See the Python code
print(3 == 3) # True
print(3 > 5) # FalseMake the order clear
Multiplication has higher precedence.
Evaluate 3 * 4.
Finish with 2 + 12.
Parentheses can change the order: (2 + 3) * 4 is 20.
Multiplication and division normally happen before addition and subtraction. Parentheses change the order: 2 + 3 * 4 is 14, while (2 + 3) * 4 is 20.
Division, floor division, and remainder with a zero divisor raise ZeroDivisionError. Check or handle invalid inputs when building real programs.
See the Python code
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20TAKE IT WITH YOU
What you have learned
- / and // perform different kinds of division.
- Comparisons return True or False.
- Parentheses make evaluation order explicit.
Answer both quick checks correctly to mark this lesson complete. You can continue at any time.