Arithmetic#
Note
Source: Drawn from the SE4ML Python chapter (chapter_python.rst,
lines 196–441) and the C# edition (data/arithmetic.rst). Operator
tables, integer vs. float distinction, and math module introduction
closely follow the SE4ML presentation.
We start with integers and arithmetic — not because arithmetic is exciting, but because the symbolism should be mostly familiar.
Testing Expressions in the Shell#
Python’s interactive shell is perfect for trying out arithmetic. Start it
with python3 and type expressions at the >>> prompt:
>>> 2 + 3
5
>>> 10 - 4
6
>>> 3 * 7
21
The shell evaluates the expression and prints the result immediately. This is much faster than writing a whole program for small experiments.
Numeric Types#
Python has two main numeric types for beginners:
intWhole numbers, positive or negative, with no fractional part:
0,42,-17,1000000.Python integers have unlimited precision — they can be as large as your computer’s memory allows. There is no overflow.
floatApproximate real numbers, written with a decimal point or an exponent:
.2,2.0,20.,2000e-1,2E3.
>>> type(42)
<class 'int'>
>>> type(3.14)
<class 'float'>
Arithmetic Operators#
The arithmetic operators in Python are:
Operator |
Meaning |
Example |
|---|---|---|
|
Addition |
|
|
Subtraction |
|
|
Multiplication |
|
|
Division (always float) |
|
|
Floor division (integer result) |
|
|
Remainder (modulus) |
|
|
Exponentiation |
|
|
Negation (unary) |
|
A key difference from many other languages: / always produces a
float, even if both operands are integers:
>>> 7 / 2
3.5
>>> 6 / 2
3.0
Use // when you want a whole-number result:
>>> 7 // 2
3
>>> -7 // 2
-4
Operator Precedence#
Python follows the standard mathematical order of operations. From highest to lowest precedence:
**(exponentiation, right to left)-x(unary negation)*,/,//,%(multiplication and division)+,-(addition and subtraction)
Use parentheses to override the default order:
>>> 2 + 3 * 4
14
>>> (2 + 3) * 4
20
See the appendix for the complete precedence table.
Mixed Arithmetic#
When you mix int and float in an expression, Python converts the
int to float automatically:
>>> 1 + 2.0
3.0
>>> type(1 + 2)
<class 'int'>
>>> type(1 + 2.0)
<class 'float'>
This widening conversion preserves the value.
Useful Built-in Functions#
Python provides several useful arithmetic functions built in — no import needed:
Function |
Description |
|---|---|
|
Absolute value of |
|
Round to nearest integer |
|
Round to |
|
Returns |
|
|
|
Largest value |
|
Smallest value |
>>> abs(-7)
7
>>> round(3.14159, 2)
3.14
>>> divmod(17, 5)
(3, 2)
The math module provides more functions. Import it first:
>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> math.pi
3.141592653589793
>>> math.floor(3.7)
3
>>> math.ceil(3.2)
4