Python Data Types

Python supports various data types to handle different kinds of data. These data types define the type of value a variable can hold. Understanding data types is essential for effective programming in Python.


1. Numeric Data Types

Python provides three primary numeric data types:

  • Integer (int): Whole numbers, positive or negative.
  • Floating Point (float): Decimal numbers.
  • Complex Numbers (complex): Numbers with a real and an imaginary part.

Examples:

x = 10        # Integer
y = 3.14      # Float
z = 2 + 3j    # Complex Number

print(type(x))  # Output: <class 'int'>
print(type(y))  # Output: <class 'float'>
print(type(z))  # Output: <class 'complex'>

2. String Data Type

Strings (str) represent text and are enclosed in single (') or double (") quotes.

Examples:

name = "Alice"
greeting = 'Hello, World!'

print(type(name))  # Output: <class 'str'>

Multiline strings use triple quotes:

message = """This is 
a multiline 
string."""

3. Boolean Data Type

Boolean (bool) represents two values: True or False.

is_python_fun = True
is_java_hard = False

print(type(is_python_fun))  # Output: <class 'bool'>

4. List Data Type

Lists (list) are ordered, mutable (changeable) collections of items.

fruits = ["Apple", "Banana", "Cherry"]
fruits.append("Orange")  # Adds an item

print(fruits[0])  # Output: Apple
print(type(fruits))  # Output: <class 'list'>

5. Tuple Data Type

Tuples (tuple) are ordered but immutable (cannot be changed after creation).

colors = ("Red", "Green", "Blue")

print(colors[1])  # Output: Green
print(type(colors))  # Output: <class 'tuple'>

6. Set Data Type

Sets (set) store unique items in an unordered collection.

numbers = {1, 2, 3, 4, 4, 5}  # Duplicate 4 is ignored

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

7. Dictionary Data Type

Dictionaries (dict) store key-value pairs.

person = {"name": "Alice", "age": 25, "city": "New York"}

print(person["name"])  # Output: Alice
print(type(person))  # Output: <class 'dict'>

8. NoneType

The None type represents the absence of a value.

result = None

print(type(result))  # Output: <class 'NoneType'>

9. Type Conversion

Python allows converting data types using built-in functions:

  • int() – Converts to an integer.
  • float() – Converts to a floating-point number.
  • str() – Converts to a string.
  • bool() – Converts to a boolean.
  • list() – Converts to a list.

Examples:

x = "10"
y = int(x)  # Converts string to integer

print(y, type(y))  # Output: 10 <class 'int'>

Understanding Python’s data types is crucial for writing efficient and error-free programs. These data types allow developers to store and manipulate different types of data effectively.