Python Data Types
Data types are a crucial concept in programming. In Python, data types define the kind of data a variable can hold, such as integers, floating-point numbers, strings, and more. Understanding data types is essential for effective coding, as they determine what operations can be performed on the data.
What Are Variables????
Variables are named storage containers used to hold data values in a program. In Python, variables are dynamically typed, meaning they can hold data of any type, and their type can change during the program’s execution.
For example:
a = 5 # 'a' is a variable holding the value 5
Dynamic Typing in Python
In Python, variables do not need to be declared with a specific data type. The data type is inferred from the value assigned to the variable and can change as needed during the program.
For example:
x = 10 # 'x' is initially an integer
print(type(x)) # Output: <class 'int'>
x = "India" # 'x' is now changed to a string
print(type(x)) # Output: <class 'str'>
Why Are Data Types Important?
Data types specify how the interpreter and program interact with data. They determine:
- What operations can be performed on the data.
- How much memory the data occupies.
- The methods and functions applicable to the data.
Python Data Types
Python supports several built-in data types, each designed to handle specific kinds of information. Here’s an overview:
Data Type | Class(es) | Description |
---|---|---|
Numeric | int , float , complex | Stores numeric values, including integers, decimals, and complex numbers. |
String | str | Holds sequences of characters. |
Sequence | list , tuple , range , bool , set , frozenset | Stores collections of items, including ordered (like lists, tuples) and unordered (like sets) collections. |
Mapping | dict | Maintains data in key-value pairs. |
None Type | NoneType | Represents the absence of a value or null. |
Boolean | bool | Represents logical values: True or False . |
Set | set , frozenset | Stores a collection of unique items. |
In Python, each data type is implemented as a class. These classes provide built-in methods and functionalities that allow you to interact with and manipulate data efficiently.
To write efficient programs, it’s essential to choose the right data type. Let’s explore the various data types available in Python.
1. Numeric Data Types
-
Integer (
int
): Whole numbers (positive or negative), without a decimal point.marks = 20 Rno = 12 x = -4
-
Float (
float
): Numbers with decimals. Even an integer stored as a float is represented with a decimal (e.g.,9.0
).weight = 56.8 y = -10.5
-
Complex (
complex
): Numbers with a real and imaginary part.distance = 2 + 1j
2. Boolean Data Type
The Boolean type represents truth values: True
or False
. You can also use 1
for True
and 0
for False
.
state = False
print(type(state)) # Output: <class 'bool'>
3. Dictionary Data Type
A dictionary is an unordered set of key-value pairs, defined using curly braces {}
. Each key must be unique, while values can repeat.
medals = {'TeamA': 25, 'TeamB': 32, 'TeamC': 14}
4. Sequence Data Types
-
String (
str
): Holds any type of characters, enclosed in single (' '
) or double quotes (" "
).Houseno = 'B-19' name = "Neer"
-
List (
list
): A compound data type holding a group of values, defined using square brackets[ ]
. Lists are mutable.student = [12, 'Niyasa', 60.5] vowels = ['a', 'e', 'i', 'o', 'u'] marks = [21, 20, 17, 24]
-
Tuple (
tuple
): Similar to lists but immutable, defined using round brackets( )
.days = ('Mon', 'Tue', 'Wed')
Indexing in Python
In sequence data types like strings, lists, and tuples, each element is assigned a unique position called an index. Indexing allows you to access individual elements from a sequence. Python supports two types of indexing:
- Forward Indexing: Starts from
0
for the first element and increments by 1 for each subsequent element. - Backward Indexing: Starts from
-1
for the last element and decrements by 1 for each previous element.
Accessing Characters in a String
string1 = "PYTHONFORALL"
# Accessing elements using forward indexing
print(string1[4]) # Output: O
# Accessing elements using backward indexing
print(string1[-4]) # Output: R
Accessing Elements in a List
list1 = [15, 20, 4.5, 'H']
# Accessing elements using forward indexing
print(list1[0]) # Output: 15
# Accessing elements using backward indexing
print(list1[-1]) # Output: H
Data Type Conversions
Python provides several functions to convert between data types:
int()
: Converts input to an integer.float()
: Converts input to a float.str()
: Converts input to a string.chr()
: Converts an integer to its Unicode character.bool()
: Converts input toTrue
orFalse
.type()
: Displays the data type of a variable.
For example:
age = "25"
print(type(age)) # Output: <class 'str'>
age = int(age) # Convert to integer
print(type(age)) # Output: <class 'int'>
Try It Yourself
Problem 1: Check Data Types
Read your friend’s name, age, and height in feet, then display their data types.
Show Code
# Solution Example:
name = input("Enter your friend's name: ")
age = int(input("Enter their age: "))
height = float(input("Enter their height in feet: "))
print(type(name), type(age), type(height))
Problem 2: Identify Data Types in a List
Create a program that takes a list of mixed data types as input and displays the type of each element in the list.
Show Code
# Solution Example:
data_list = [123, "Python", 45.67, True, None, [1, 2, 3], {"key": "value"}]
print(f"Element: {data_list[0]} - Type: {type(data_list[0])}")
print(f"Element: {data_list[1]} - Type: {type(data_list[1])}")
print(f"Element: {data_list[2]} - Type: {type(data_list[2])}")
print(f"Element: {data_list[3]} - Type: {type(data_list[3])}")
print(f"Element: {data_list[4]} - Type: {type(data_list[4])}")
print(f"Element: {data_list[5]} - Type: {type(data_list[5])}")
print(f"Element: {data_list[6]} - Type: {type(data_list[6])}")