Data Types

What Are Data Types?

Data types tell us what kind of data we're working with, like numbers, text, or more complex structures. Knowing the data type helps us decide how to use and manipulate the data.

Built-in Data Types in Python:

Here are the different categories of data types in Python:

  • Text Type: str
  • Numeric Types: int, float
  • Sequence Types: list, tuple, range
  • Mapping Type: dict
  • Set Types: set
  • Boolean Type: bool
  • None Type: NoneType

Getting the Data Type:

  • Use the type() function to find out the data type of any object.

    x = 20.5
    #display x:
    print(x)
    #display the data type of x:
    print(type(x)) 

    Output: 20.5 <class 'float'>

Setting the Data Type:

  • Data type is set when you assign a value to a variable.

    x = "Hello World"  # str
    x = 20  # int
    x = 20.5  # float
    x = ["apple", "banana", "cherry"]  # list
    x = ("apple", "banana", "cherry")  # tuple
    x = range(6)  # range
    x = {"name": "John", "age": 36}  # dict
    x = {"apple", "banana", "cherry"}  # set
    x = True  # bool
    x = None  # NoneType
    

Setting Specific Data Types:

  • You can also use constructor functions to set the data type.

    x = str("Hello World")  # str
    x = int(20)  # int
    x = float(20.5)  # float
    x = list(("apple", "banana", "cherry"))  # list
    x = tuple(("apple", "banana", "cherry"))  # tuple
    x = range(6)  # range
    x = dict(name="John", age=36)  # dict
    x = set(("apple", "banana", "cherry"))  # set
    x = bool(5)  # bool
    
    

Summary:

  • Understanding data types in Python is crucial. They help you know how to work with and manipulate data effectively. Practice creating and using different data types to get comfortable with Python programming