Python includes robust support for numerical operations, making it easy to perform arithmetic calculations. The Python interpreter can act as a sophisticated calculator where expressions can be evaluated directly.
Basic Arithmetic
The basic arithmetic operators in Python are:
- Addition (`+`): Adds two numbers.
- Subtraction (`-`): Subtracts the second number from the first.
- Multiplication (`*`): Multiplies two numbers.
- Division (`/`): Divides the first number by the second and always returns a float.
For example:
```python
>>> 5 + 3
8
>>> 10 - 4
6
>>> 7 * 6
42
>>> 8 / 2
4.0
```
Grouping with Parentheses
Parentheses `()` can be used to group expressions to control the order of operations:
```python
>>> 5 + 3 * 2
11
>>> (5 + 3) * 2
16
```
Floor Division and Modulus
- Floor Division (`//`): Divides and returns the integer part of the quotient.
- Modulus (`%`): Returns the remainder of the division.
Examples:
```python
>>> 9 // 2
4
>>> 9 % 2
1
```
Exponentiation
Python uses the `**` operator for exponentiation:
```python
>>> 2 ** 3
8
>>> (-3) ** 2
9
```
Note the difference between `-3**2` and `(-3)**2`:
```python
>>> -3 ** 2
-9
>>> (-3) ** 2
9
```
The expression `-3**2` is interpreted as `-(3**2)`.
Variable Assignment
The equal sign `=` is used to assign values to variables:
```python
>>> x = 5
>>> y = 3
>>> x * y
15
```
Attempting to use an undefined variable results in an error:
```python
>>> z
NameError: name 'z' is not defined
```
Floating-Point Arithmetic
Python supports floating-point arithmetic. Mixed type arithmetic between integers and floats results in a float:
```python
>>> 1 + 2.0
3.0
```
Interactive Mode and `_` Variable
In interactive mode, the last evaluated expression is assigned to the special variable `_`:
```python
>>> 7 * 3
21
>>> _
21
```
This variable should be treated as read-only, and assigning a value to it is not recommended.
Other Numeric Types
Python supports additional numeric types:
- Decimal: For fixed-point and floating-point arithmetic with more precision and control.
- Fraction: For rational number arithmetic.
Examples with the `decimal` and `fractions` modules:
```python
from decimal import Decimal
from fractions import Fraction
d = Decimal('0.1') + Decimal('0.2')
f = Fraction(1, 3) + Fraction(1, 3)
```
Complex Numbers
Python has built-in support for complex numbers. Complex numbers have a real and an imaginary part, with the imaginary part indicated by `j` or `J`:
```python
>>> 1 + 2j
(1+2j)
>>> (1 + 2j) * (1 - 2j)
(5+0j)
```