Python Numbers

Numbers are primitive data types in Python. There are three sub-types of numeric data, namely:

  • int
  • float
  • complex

Python Numbers

int is used for integers ranging from -∞ to +∞

float represents decimal numbers with floating-point.

complex is of the form a+bj where a and b are integers and j is an imaginary number.

type() function can be used to get numeric object data types as well. int(), float(), complex() can be used respectively to typecast into integer, float and complex respectively.

Example:

    >>> x = 1
    >>> type(x)
    int
    >>> y = 1.35
    >>> type(y)
    float
    >>> z = 1+2j
    >>> type(z)
    complex                          

Random Numbers

Python has a built-in module random to work with random numbers. Commonly used random number functions are as follows:

import random

  • random.random(): Generates a random number.
  • random.randint(start, end): Selects a random integer between the given start and endpoints, including the boundary values.
  • random.randrange(start, end): Selects a random integer between the given start and endpoints. Endpoint boundary value is not included.
  • random.choice(iterable): Selects a random number from a given iterable-like list.
  • random. choices(iterable, size): Selects given size of random numbers from the given iterable with duplicate selections.
  • random. sample(iterable, size): Selects given size of random numbers from the given iterable without duplicate selections.
  • random.seed(number): Random numbers are generated with a random seed or starting values from the timestamp, noise, etc. If we put a number as seed values the random number generated will be the same every time.
  • random.shuffle(iterable): Gives a random shuffle to the given iterable-like list.

Django training in Bangalore