Working with Numbers#

In a previous chapter Variables and Types a short introduction to integers for numerical values was made. Python has three numerical data types and they’re the following types integer, float, and complex.

The basics about numbers#

Python determines the data type when a variable is assigned to a value and with the type function the data type can be determined. The example below uses different types and prints the data type with the type function.

Example of the different numerical data types#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     # Negative integer number
 5     q = -1
 6     # Positive integer number
 7     x = 1
 8     # Floating-point number
 9     y = 3.14
10     # Complex number
11     z = 1j
12     print(type(q))
13     print(type(x))
14     print(type(y))
15     print(type(z))
16
17
18 if __name__ == "__main__":
19     main()

The output below of the example above shows data types Python is using. This confirms how the values were specified in the example.

Output#
1<class 'int'>
2<class 'int'>
3<class 'float'>
4<class 'complex'>

Type conversion#

Python determines the type when the variable is assigned and can not be changed, but Python does allow type conversion. This allows for an integer to be converted to a float and vice versa as is show in the example below where int and float are used to create a new value and assign it to a new variable.

Example converting integers and floats#
 1#!/usr/bin/env python3
 2
 3def main():
 4    x = 1
 5    y = 3.14
 6    z = 1j
 7
 8    a = float(x)
 9    b = int(y)
10
11    print(a)
12    print(b)
13
14    print(type(a))
15    print(type(b))
16
17
18if __name__ == "__main__":
19    main()

The output below shows the new values and the matching type for the variable.

Output#
11.0
23
3<class 'float'>
4<class 'int'>

Complex numbers cannot be converted into another number type as there is no defined way to converted these to an integer or float. The example below generates an TypeError when the conversion needs to happen and stops the program.

Example converting a complex number to an integer#
 1#!/usr/bin/env python3
 2
 3def main():
 4    x = 1
 5    y = 3.14
 6    z = 1j
 7
 8    c = int(1j)
 9
10    print(c)
11
12    print(type(c))
13
14
15if __name__ == "__main__":
16    main()
Output#
1Traceback (most recent call last):
2  File "/workspaces/learning-python/example.py", line 8, in <module>
3TypeError: can't convert complex to int

Generate a random number#

The module random can be imported to use the function random.randrange() to generated random numbers within a certain range. The example below generates a number between 1 and 10.

Example#
 1 #!/usr/bin/env python3
 2
 3 import random
 4
 5 def main():
 6     print(random.randrange(1, 10))
 7
 8
 9 if __name__ == "__main__":
10     main()

Other known function is random.randint() to generate an integer like random.randrange(), but the second paramater will also be included as a possible outcome. The second function is random.seed() that can be used to seed the module with specific value to generate all random numbers. By default the current timestamp is used, but by selecting a specific value the sequence becomes predictable what can be useful for testing purposes.

Note

The behavior of random.randrange() has changed and will only accept integer paramaters since Python 3.10 otherwise a ValueError or TypeError will be generated.

Absolute value#

The built-in function abs() returns the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing __abs__(). If the argument is a complex number, its magnitude is returned.

Example#
 1 #!/usr/bin/env python3
 2
 3 import random
 4
 5 def main():
 6     print(abs(-1))
 7
 8
 9 if __name__ == "__main__":
10     main()
Output#
1 1

Using the math module#

For advanced math functions the module math is shipped with Python and contains higher level math function like math.sqrt() and math.pow(), but also mathematical constants like math.pi. The example below also shows math.ceil() and math.floor().

Example#
 1 #!/usr/bin/env python3
 2
 3 import math
 4
 5 def main():
 6     # print Pi
 7     print(math.pi)
 8     # Determine the smallest integer greater than or equal
 9     print(math.ceil(8.3))
10     # Determine the largest integer smaller than or equal
11     print(math.floor(8.3))
12     # Print the square root
13     print(math.sqrt(9))
14
15
16 if __name__ == "__main__":
17     main()
Output#
1 3.141592653589793
2 9
3 8
4 3.0

Note

The example above shows math.pow() for when floats are involved. There are also ** and pow() to do square root calculation, but those are mend to be used with integer operations.

Converting positional numeral systems#

Converting between positional numeral systems like decimal, binary, octal, and hexadecimal can easily be done in Python as they’re internally all of type integer, but the representation is different. With the functions bin(), hex(), and oct() the required representation can be generated. Also with the function int the integer value can be shown as can be seen in the example and output below.

Example#
 1 #!/usr/bin/env python3
 2
 3 import math
 4
 5 def main():
 6     value_dec = 128
 7     value_bin = 0b10000000
 8     value_oct = 0o200
 9     value_hex = 0x80
10
11     print("The value_decimal value of", value_dec, "is:")
12     print(bin(value_dec), "in binary.")
13     print(oct(value_dec), "in octal.")
14     print(hex(value_dec), "in hexadecimal.")
15
16     print("The binary value of", (value_bin), "is:")
17     print(int(value_bin), "in decimal.")
18     print(oct(value_bin), "in octal.")
19     print(hex(value_bin), "in hexadecimal.")
20
21     print("The octal value of", oct(value_oct), "is:")
22     print(int(value_oct), "in decimal.")
23     print(bin(value_oct), "in binary.")
24     print(hex(value_oct), "in hexadecimal.")
25
26     print("The hexvalue_decimal value of", hex(value_hex), "is:")
27     print(int(value_hex), "in decimal.")
28     print(bin(value_hex), "in binary.")
29     print(oct(value_hex), "in octal.")
30
31
32 if __name__ == "__main__":
33     main()
Output#
 1 The value_decimal value of 128 is:
 2 0b10000000 in binary.
 3 0o200 in octal.
 4 0x80 in hexadecimal.
 5 The binary value of 128 is:
 6 128 in decimal.
 7 0o200 in octal.
 8 0x80 in hexadecimal.
 9 The octal value of 0o200 is:
10 128 in decimal.
11 0b10000000 in binary.
12 0x80 in hexadecimal.
13 The hexvalue_decimal value of 0x80 is:
14 128 in decimal.
15 0b10000000 in binary.
16 0o200 in octal.