Social Media

Python Data Types

 

Understanding Python Data Types

Python is a dynamically typed language, meaning you don’t need to declare the type of a variable explicitly. It automatically determines the data type based on the assigned value. In this blog, we will explore the 10 fundamental data types in Python.

1. Integer (int)

The int type is used to store whole numbers, both positive and negative.


x = 10
y = -5  
z = 1000  
print(type(x))  # Output: <class 'int'>

Explanation:

In this example, we define three integer variables (x, y, and z). The type() function returns their data type, which is int.

2. Floating-Point (float)

The float type stores decimal numbers (floating-point values).

a = 3.14  
b = -0.5  
c = 2.0  
print(type(a))  # Output: <class 'float'>  

3. Boolean (bool)

Booleans represent truth values: True or False. They are often used in conditional statements.

is_python_fun = True  
is_raining = False  
print(type(is_python_fun))  # Output: <class 'bool'>

4. String (str)

A str stores a sequence of characters (text). Strings are enclosed in single ('), double (") or triple quotes (""").

name = "Hari"  
greeting = 'Hello, Python!'  
print(type(name))  # Output: <class 'str'>

5. Complex (complex)

The complex type is used for complex numbers (numbers with a real and imaginary part).

num = 3 + 4j  
print(type(num))  # Output: <class 'complex'>

6. List (list)

A list is an ordered, mutable collection that allows duplicate elements. Lists are defined using square brackets [].

fruits = ["apple", "banana", "cherry"]  
numbers = [1, 2, 3, 4]  
print(type(fruits))  # Output: <class 'list'>

7. Tuple (tuple)

A tuple is similar to a list but immutable (cannot be changed after creation). Defined using parentheses ().

coordinates = (10.5, 20.7)  
colors = ("red", "blue", "green")  
print(type(coordinates))  # Output: <class 'tuple'>

8. Dictionary (dict)

A dict is a collection of key-value pairs, defined using curly braces {}.

student = {"name": "Hari", "age": 24, "city": "Bengaluru"}  
print(type(student))  # Output: <class 'dict'>

9. Set (set)

A set is an unordered collection of unique elements, defined using curly braces {}.

unique_numbers = {1, 2, 3, 4, 4, 5}  
print(unique_numbers)  # Output: {1, 2, 3, 4, 5} (removes duplicates)
print(type(unique_numbers))  # Output: <class 'set'>

10. Frozen Set (frozenset)

A frozenset is an immutable version of a set, created using frozenset().

frozen_numbers = frozenset({1, 2, 3, 4})  
print(type(frozen_numbers))  # Output: <class 'frozenset'>

Conclusion

Python provides a variety of built-in data types to handle different types of values. Understanding these types is crucial for writing efficient and bug-free code.

Comments