Learning Python

7. Numbers

  • int
  • float
  • complex

7.1. The basics about numbers

#!/usr/bin/env python3

def main():
    q = -1
    x = 1
    y = 3.14
    z = 1j
    print(type(q))
    print(type(x))
    print(type(y))
    print(type(z))


if __name__ == "__main__":
    main()
<class 'int'>
<class 'int'>
<class 'float'>
<class 'complex'>

7.2. Type conversion

Complex numbers cannot be converted into another number type

#!/usr/bin/env python3

def main():
    x = 1
    y = 3.14
    z = 1j

    a = float(x)
    b = float(y)

    print(a)
    print(b)

    print(type(a))
    print(type(b))


if __name__ == "__main__":
    main()

7.3. Generate a random number

#!/usr/bin/env python3

import random

def main():
    print(random.randrange(1, 10))


if __name__ == "__main__":
    main()

randint and seed

7.4. Absolute value

#!/usr/bin/env python3

import random

def main():
    print(abs(-1))


if __name__ == "__main__":
    main()

Output:

1

7.5. Using the math module

A math modules ships with Python for advanced calculations.

#!/usr/bin/env python3

import math

def main():
    # print Pi
    print(math.pi)
    # Determine the smallest integer greater than or equal
    print(math.ceil(8.3))
    # Determine the largest integer smaller than or equal
    print(math.floor(8.3))
    # Print the square root
    print(math.sqrt(9))


if __name__ == "__main__":
    main()

Output:

3.141592653589793
9
8
3.0

7.6. Converting between decimal, binary, octal, and hexadecimal

#!/usr/bin/env python3

import math

def main():
    value_dec = 128
    value_bin = 0b10000000
    value_oct = 0o200
    value_hex = 0x80

    print("The value_decimal value of", value_dec, "is:")
    print(bin(value_dec), "in binary.")
    print(oct(value_dec), "in octal.")
    print(hex(value_dec), "in hexadecimal.")

    print("The binary value of", (value_bin), "is:")
    print(int(value_bin), "in decimal.")
    print(oct(value_bin), "in octal.")
    print(hex(value_bin), "in hexadecimal.")

    print("The octal value of", oct(value_oct), "is:")
    print(int(value_oct), "in decimal.")
    print(bin(value_oct), "in binary.")
    print(hex(value_oct), "in hexadecimal.")

    print("The hexvalue_decimal value of", hex(value_hex), "is:")
    print(int(value_hex), "in decimal.")
    print(bin(value_hex), "in binary.")
    print(oct(value_hex), "in octal.")


if __name__ == "__main__":
    main()

Output:

The value_decimal value of 128 is:
0b10000000 in binary.
0o200 in octal.
0x80 in hexadecimal.
The binary value of 128 is:
128 in decimal.
0o200 in octal.
0x80 in hexadecimal.
The octal value of 0o200 is:
128 in decimal.
0b10000000 in binary.
0x80 in hexadecimal.
The hexvalue_decimal value of 0x80 is:
128 in decimal.
0b10000000 in binary.
0o200 in octal.