Python – Data Types

Understanding what data types are accessible and how data is stored, retrieved, and manipulated in a programming language is one of the most crucial aspects of learning any programming language. Python is an object-oriented programming language in which everything is an object and every value has a datatype. Data types are thus classes in Python, and variables are instances (objects) of these classes.

In Python, there are several data types that may be classified as follows:

Category Data Types
Text str
Numeric int, float, complex
Sequence list, tuple, range
Mapping dict
Set set, frozenset
Boolean bool
Binary bytes, bytearray, memoryview

type() function

The type() method in Python is used to determine the datatype of a variable. Take a look at the sample below.

MyInt = 10
print(type(MyInt))

MyFloat = 10.5
print(type(MyFloat))

The output of the above code will be:

<class 'int'>
<class 'float'>

Set data type of a variable

Python, unlike Java and C++, does not need the declaration of a variable or its data type. When a value is assigned to a variable, the data type is set. The table below shows how to set various data types in variable x.

Data Types Example
str x = “Hello World!” or x = ‘Hello World!’
int x = 10
float x = 10.5
complex x = 5 + 5j
list x = [1, 2, 3]
tuple x = (1, 2, 3)
range x = range(1, 5)
dict x = {‘name’: ‘John’, ‘age’: 25}
Set x = {1, 2, 3}
frozenset x = frozenset({1, 2, 3})
bool x = True
bytes x = b”Hello World!”
bytearray x = bytearray(3)
memoryview x = memoryview(bytes(3))

Set datatype of a variable using constructor

Data types are classes in Python, and variables are instances (objects) of these classes, as previously stated. These data type classes feature a built-in method called a function Object(). That may be used to create an object instance. The table below shows how to use the function Object() { [native code] } to set different data types in variable x.

Data Types Constructor Example
str str() x = str(“Hello World!”) or x = str(‘Hello World!’)
int int() x = int(10)
float float() x = float(10.5)
complex complex() x = complex(5 + 5j)
list list() x = list((1, 2, 3))
tuple tuple() x = tuple((1, 2, 3))
range range() x = range(1, 5)
dict dict() x = dict(name=’John’, age=25)
Set set() x = set((1, 2, 3))
frozenset frozenset() x = frozenset((1, 2, 3)
bool bool() x = boot(1)
bytes byte() x = bytes(3)
bytearray bytearray() x = bytearray(3)
memoryview memoryview() x = memoryview(bytes(3))

Also Read: Java – Data Types

Click Here for an online python compiler.

Leave a Reply

Your email address will not be published.