Data Types in Python

Rina Mondal
2 min readDec 25, 2023

--

A data type of a variable in programming refers to the kind of value a variable can hold and the operations that can be performed on it. Python is a dynamically typed language, which means that no need to explicitly declare the data type of a variable when you create it. However, Python still has several built-in data types.

Here are some of the common ones:

1. Numeric Types:
int: Integer type, e.g., x = 5
float: Floating-point type, e.g., y = 3.14
complex: Complex number type, e.g., z = 2 + 3j

2. Sequence Types:
str: String type, e.g., s = “Hello, World!
list: List type, e.g., my_list = [1, 2, 3]
tuple: Tuple type, e.g., my_tuple = (1, 2, 3)

3. Set Types:
set: Unordered collection of unique elements, e.g., my_set = {1, 2, 3}

4. Mapping Type:
dict: Dictionary type, e.g., my_dict = {‘key’: ‘value’}

# Simple dictionary with minimal key-value pairs

# Creating a dictionary
person = {'name': 'Rani', 'age': 30}


print("Name:", person['name'])
print("Age:", person['age'])

#O/t- Name:
Alice
Age: 30

5. Boolean Type:
bool: Boolean type, either True or False.

# Simple program to check if a number is even

number = 4
is_even = (number % 2 == 0)
print(f"{number} is even: {is_even}")

#O/t-4 is even: True.

6. None Type:
NoneType: Represents the absence of a value, often used as a default return value of functions that don’t explicitly return anything.

# Function that prints a greeting or does nothing if the name is not provided

def greet(name=None):
if name is not None:
print(f"Hello, {name}!")
else:
print("Hello, anonymous!")


greet("Alice")
greet() # Output: Hel

#O/t- Hello, Alice!
Hello, anonymous!

7. Sequence Types (Advanced):
range: Represents an immutable sequence of numbers, often used in loops, e.g., Using range in a for loop to print numbers from 0 to 4

for i in range(5):
print(i)

#O/t= 0,1,2,3,4 (excludes the last number)

8. Binary Types:
bytes: Immutable sequence of bytes
bytearray: Mutable sequence of bytes

# Creating and manipulating a bytearray

# Create a bytearray object from a string
my_bytearray = bytearray(b'Hello, World!')


# Display the original bytearray
print("Original Bytearray:", my_bytearray)


# Modify individual bytes
my_bytearray[0] = 74 # ASCII code for 'H'
my_bytearray[-1] = 33 # ASCII code for '!'


# Display the modified bytearray
print("Modified Bytearray:", my_bytearray)


#O/t- Original Bytearray: bytearray(b'Hello, World!')
Modified Bytearray: bytearray(b'Jello, World!')

These data types provide a flexible way to work with different kinds of data in Python.

Detailed Explanation in YouTube:

Download Code from Github: https://github.com/datascience-1100/Variables-in-Python/blob/main/Basic%20Data%20types%20and%20variables%20in%20Python.ipynb

--

--

Rina Mondal

I have an 8 years of experience and I always enjoyed writing articles. If you appreciate my hard work, please follow me, then only I can continue my passion.