Python Data Types

In Python, every value has a specific data type that determines the operations that can be performed on it and the way it is stored. Python is a dynamically typed language, meaning you don't need to declare the type of a variable when you assign it a value. The interpreter automatically assigns the appropriate type based on the value.

Example:

a = 5

In the example above, the variable a is assigned the value 5, and Python automatically interprets a as an integer (int). You can verify the type of a variable using the type() function.

Example:

a = 15
b = "Hello Python"
c = 15.5

print(type(a)) # Outputs: <class 'int'>
print(type(b)) # Outputs: <class 'str'>
print(type(c)) # Outputs: < class 'float'>

Standard Data Types in Python

Python provides several built-in data types that define how data is stored and manipulated. These are categorized into the following types:

Numbers: int, float, complex

Sequence Type: str, list, tuple

Boolean: bool

Set: set

Dictionary: dict

1. Numbers

Integer (int): Whole numbers, positive or negative, without a decimal point.

Float (float): Numbers with a decimal point.

Complex (complex): Numbers with a real and imaginary part.

x = 5 # int
y = 3.14 # float
z = 1 + 2j # complex

2. Sequence Type

String (str): A sequence of characters enclosed in quotes.

List (list): An ordered collection of values, which can be of any type, enclosed in square brackets.

Tuple (tuple): Similar to a list, but immutable, meaning it cannot be changed after creation. Enclosed in parentheses.

s = "Hello" # str
lst = [1, 2, "Python"] # list
tpl = (1, 2, "Python") # tuple

3. Boolean (bool)

Represents one of two values: True or False. Used for logical operations and conditions.

isValid = True # bool
isActive = False # bool

4. Set

• An unordered collection of unique items. Sets are mutable but do not allow duplicate elements.

mySet = {1, 2, 3, 4, 5}
anotherSet = set([1, 2, 3])

5. Dictionary (dict)

• A collection of key-value pairs. Each key is unique, and the values can be of any type. Dictionaries are mutable.

myDict = {"name": "John", "age": 25}

Using type() Function

The type() function is used to determine the type of a variable or value in Python. It returns the type as a class.

Example:

x = 10
print(type(x)) # Outputs: < class 'int'>