Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


Data types in Python

Educative Answers Team

The data type of a variable or object determines which operations can be applied to it. Once a variable is assigned a data type, it can be used for computations in the program.

The best thing about Python is that the data type doesn’t need to be defined when declaring a variable. Data types exist, but the variables are not bound to any of them. Languages that act in this way are called​ ​dynamically typed languages.

Variations of data types

There are two kinds of data types, both of which are​ further divided into sub-types:

  • Primitive data types: Data types which are pre-defined and supported by the programming language.

  • Non-primitive data types: Data types which are derived from the primitive data types and offer increased functionality. ​​

svg viewer

Primitive data sub-types

1. Integer​

Integers represent numeric data – they represent whole numbers from negative infinity to infinity.

integer_1 = 100
integer_2 = 50

# various operations on integers
print (integer_1*integer_2)
print (integer_1+integer_2)
print (integer_1-integer_2)
print (integer_1/integer_2)

2. String

Strings are used to store data that involves characters (e.g., names or addresses). Strings can be created in Python by enclosing a sequence of characters within a pair of single or double-quotes.

string_1 = "Hello"
string_2 = "World"
print (string_1 + string_2)

3. Boolean

Boolean type only has two types of return values: True and False. These return values are interchangeable with the integers 1 and 0.

# has_passed is a boolean

# false is assigned to has_passed (a boolean)
has_passed = False
marks = 80
if (marks > 50):
    # true has been assigned to has_passed (a boolean)    
    has_passed = True

print (has_passed)

4. Float

Floating points are used for rational numbers that usually end with a decimal figure.

float_1 = 12.539
float_2 = 6.78

# various operations on floats
print (float_1*float_2)
print (float_1+float_2)
print (float_1-float_2)
print (float_1/float_2)

Non-Primitive data sub-types

1. Lists

Python Lists are used to store collections of heterogeneous items; they can be recognized by their square brackets which​ hold elements and are ​separated by a comma.

fruits = ["Apple", "Banana", "Kiwi", "Mango"]

# various len functions
print (len(fruits))
print (fruits)

2. Dictionaries

A dictionary is an unordered, changeable, and indexed collection of elements. In Python, dictionaries are written with curly brackets and contain​ keys and values. See the code below:

my_car =	{
  "brand": "Suzuki",
  "model": "Mehran",
  "year": 2001

# indexing the dict
print "The brand of my car is ", my_car["brand"]


Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring