Python is a versatile and widely-used programming language that supports various programming paradigms, including functional, procedural, and object-oriented programming. One of its fundamental features is its ability to perform arithmetic operations effortlessly.
Basic Arithmetic Operations
Python provides built-in support for standard arithmetic operations. These can be performed interactively using the Python shell (REPL).
>>> 3 + 5 # Addition
8
>>> 10 - 4 # Subtraction
6
>>> 10 * 4 # Multiplication
40
>>> 10 / 4 # Division (returns a float)
2.5
>>> 10 // 4 # Floor division (integer result)
2
>>> 10 % 4 # Modulus (remainder)
2
>>> 2 ** 3 # Exponentiation (power)
8
Assigning Values to Multiple Variables
Python allows assigning a single value to multiple variables simultaneously:
>>> x = y = z = 0
>>> print(x, y, z)
0 0 0
You can also assign different values to multiple variables in a single line:
>>> a, b, c = 5, 10, 15
>>> print(a, b, c)
5 10 15
Working with Complex Numbers
Python natively supports complex numbers. Imaginary numbers are written with a suffix j or J. The real and imaginary parts of a complex number can be accessed using the .real and .imag attributes:
>>> z = 3 + 4j
>>> z.real
3.0
>>> z.imag
4.0
>>> -1j * 1j # Multiplying imaginary numbers
(1+0j)
Using the Last Evaluated Result (_)
In interactive mode (Python shell), the last printed value is automatically assigned to the special variable _:
>>> a = 678
>>> a * 23
15594
>>> print(_) # Accessing the last result
15594
>>> _ / 22 # Using the last result in another calculation
708.0
This feature is useful when performing quick calculations without explicitly storing intermediate values in variables.
Additional Considerations
- Python supports floating-point arithmetic, but be aware of precision issues due to how floating-point numbers are stored.
- The
decimalandfractionsmodules provide more precise control over numerical calculations. - Python 3 introduced
//for floor division, ensuring integer division results are consistent.
Conclusion
Python makes arithmetic operations simple and intuitive. Its support for complex numbers, multiple assignments, and interactive features like _ provide an efficient programming experience. Whether you’re working on basic calculations or advanced numerical computations, Python’s arithmetic capabilities are powerful and easy to use.