Python has several built-in data types to represent different kinds of data. The main built-in types are:
Finally, note that although Python 2.x
had both an int
and long
type, Python 3
combines the behavior of these two into a single int
type.
You can determine the data type of any object using the type()
function.
n1 = 4 #Integer literal
n2 = 1j #Complex literal
n3 = 2.32 #float literal
string_literal = "Nirmal" #string literal
true_literal = True #boolean literal
false_literal = False #boolean literal
value = None #None type literal
print(type(n1)) #<class 'int'>
print(type(n2)) #<class 'float'>
print(type(string_literal)) #<class 'str'>
print(type(true_literal)) #<class 'bool'>
print(type(false_literal)) #<class 'bool'>
print(type(value)) #<class 'NoneType'>
Exploring all datatypes
Int type
The most basic numerical type is the integer. Any number without a decimal point is an integer.
a, b = 1,2 print(type(a)) # <class 'int'> print(a+b)# 3 print(a-b)# -1
Float type
The float type in Python represents floating point numbers, which are numbers with decimal points. Floats are implemented as
64-bit
double precision values. Python floats have a large range, from around1e-308 to 1e308.
a = 1.5 b = 2.5 num3 = 1e6 # 1 million print(type(a))# <class 'float'> print(a + b) # Output = 4.0 print(a - b) # Output = -1.0 print(a * b)# Output = 3.75 print(a / b)# Output = 0.6
Some
math modules
to manipulate float :from math import floor, ceil floor(1.8) # 1 ceil(1.2) # 2 round(1.75) # 2
Complex type
Complex numbers are numbers with
real
andimaginary
parts.complex_num = 1 + 2j print(complex_num.real, complex_num.imag) # Output = 1, 2 #Some operations a = 1 + 2j b = 3 + 4j print(a + b) # (4+6j) print(a - b)# (-2-2j)
Booleans type
The Boolean type is a simple type with two possible values:
True
andFalse
, and is returned by comparison operators.a, b = 4, 5 result = (a < b) print(result) #True
Booleans can also be constructed using the
bool()
object constructor.For example, any numeric type is
False
if equal tozero
, andTrue
otherwise.print(bool(2012)) #True print(bool(1)) # True print(bool(0))# False
Similarly, The Boolean conversion of
None
is alwaysFalse
and for strings, bool(s) isFalse
forempty
strings and True otherwiseprint(bool(None)) #False(Always False for None) print(bool(""))# For empty string it is False print(bool("Nirmal")) #True
String Type
Strings are sequences of characters, represented using either
single
ordouble
quotes.name = "nirmalpandey"#assigning string to variable name print(name) # output = nirmalpandey
Strings are
immutable
, meaning once created they cannot be changed, only replaced with a new string.message = "Bitsnotion" message[0] = 'b' print(message) # This will raise a TypeError
None Type
None is returned when a function does not explicitly return a value.
x = None if x is None: print("Empty value") else: print("Available") #Output : Empty value