Python Numbers

Python Numbers – In Python, there are integers, floating-point numbers, and complex numbers. Integers and floating-point numbers are differentiated by the presence or absence of decimal points. And the output of addition and subtraction of integer and float will be floating-point numbers. In this article we will learn about python numbers.

a=5
type(a)
b=5.0
type(b)

Complex numbers are represented in the form x+yj where x is the real part and y is the imaginary part.

c=3+2j
type(c)
c+2
c+3j

Type Conversion

In python, we can convert the data types from one format to another.

An integer can be converted to float and complex numbers by the below format.

complex(3)
complex(3,2)
float(5)

Number data types like integers, float, and complex numbers can be converted to a string.

str(5)
str(5.0)
str(3+2j)

Similarly, String and float can be converted to int using int().

int('5')
int(5.6)

But we cannot convert the complex numbers to integers.

Mathematical functions

abs(x)

Positive distance between x and 0

abs(-5.1)
abs(5.1)

ceil(x)

The ceil() method returns the smallest integer value, which is greater than or equal to the specified number.

import math
math.ceil(5.1)

floor(x)

Returns the closest integer value which is less than or equal to the specified value.

import math
math.floor(5.99)

max(x1,x2,..) and min(x1,x2,x3,…)

As the name indicates max function returns the largest integer among the given arguments and min returns the smallest integer.

max(5,3,2,7)
min(5,3,2,7)

round(x,[n])

x rounded to n digits from the decimal point. ‘n’ is not mandatory.

round(5.676,2)
round(5.7)

sqrt(x)

Returns the square root of x for x>0

import math
math.sqrt(14)

pow(x,y)

Equivalent to x**y.

pow(4,2)

Random number functions

Random numbers are used in applications like games, simulations, testing, security, and privacy applications. The most commonly used functions are

choice(x1,x2,x3,..)

Returns a random number from the given sequence

import random
random.choice([4,1,7,8])

randrange(start, stop, step)

A randomly selected element from range(start, stop, step)

import random
random.randrange(1,10,2)

random()

A random float r, such that 0 is less than or equal to r and r is less than 1

import random
random.random()

shuffle([list])

Randomizes the items of a list in place. Returns None.

import random
l=[1,2,3,4]
random.shuffle(l)
print(l)

Reference

Reference1

Translate ยป