How To Declare Data Type in Python

Python has a number of built-in data types that are used to represent different kinds of data. Here are some of the main data types in Python:

  1. Integer: Integers are whole numbers, such as 1, 2, 3, -1, -2, -3, and 0. In Python, you can define an integer variable like this:

    x = 5
  2. Float: Floats are numbers with a decimal point, such as 3.14, -1.5, and 0.0. In Python, you can define a float variable like this:

    y = 3.14
  3. String: Strings are sequences of characters, such as "hello world" and "123". In Python, you can define a string variable like this:

    z = "hello world"
  4. Boolean: Booleans are either True or False. In Python, you can define a boolean variable like this:

    a = True
  5. List: A list is an ordered collection of values. In Python, you can define a list variable like this:

    b = [1, 2, 3, "four", True]
  6. Tuple: A tuple is similar to a list, but it is immutable, which means it cannot be modified once it is created. In Python, you can define a tuple variable like this:

    c = (1, 2, 3, "four", True)
  7. Dictionary: A dictionary is an unordered collection of key-value pairs. In Python, you can define a dictionary variable like this:

    d = {"name": "John", "age": 30, "city": "New York"}

Here's a simple example of a Python script that uses different data types:

  1. # Define variables of different data types
  2. x = 5
  3. y = 3.14
  4. z = "hello"
  5. a = True
  6. b = [1, 2, 3]
  7. c = (4, 5, 6)
  8. d = {"name": "John", "age": 30}
  10. # Print the variables and their types
  11. print("x =", x, "type:", type(x))
  12. print("y =", y, "type:", type(y))
  13. print("z =", z, "type:", type(z))
  14. print("a =", a, "type:", type(a))
  15. print("b =", b, "type:", type(b))
  16. print("c =", c, "type:", type(c))
  17. print("d =", d, "type:", type(d))

This script defines variables of different data types, including integers, floats, strings, booleans, lists, tuples, and dictionaries. It then prints out each variable and its data type using the print() function and the type() function, which returns the type of an object.

When you run this script, it will output the following:

  1. x = 5 type: <class 'int'>
  2. y = 3.14 type: <class 'float'>
  3. z = hello type: <class 'str'>
  4. a = True type: <class 'bool'>
  5. b = [1, 2, 3] type: <class 'list'>
  6. c = (4, 5, 6) type: <class 'tuple'>
  7. d = {'name': 'John', 'age': 30} type: <class 'dict'>

This example demonstrates how to define and use different data types in Python, as well as how to use the print() and type() functions.

These are just a few examples of the many data types available in Python. Understanding the different data types and how to use them is an important part of learning to program in Python.

Add new comment