Numbers in Python
Let's try some more python commands.
1. Numbers
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators
+, -, * and / work just like in most other languages (for example, Pascal or C); parentheses (()) can be used for grouping. For example:
The integer numbers (e.g.
2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have typefloat. We will see more about numeric types later in the tutorial.
Division (
/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you can use the // operator; to calculate the remainder you can use %:
With Python, it is possible to use the
** operator to calculate powers [1]:
The equal sign (
=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
If a variable is not “defined” (assigned a value), trying to use it will give you an error:
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
In interactive mode, the last printed expression is assigned to the variable
_. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.
In addition to
int and float, Python supports other types of numbers, such as Decimal and Fraction. Python also has built-in support for complex numbers, and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j).
Comments
Post a Comment