Data Types in Python
Python is a dynamically-typed language, which means that variables can hold values of different data types without the need for explicit declaration. Python supports a wide range of data types, each with its own characteristics and use cases. Here are the main data types in Python:
1. Numeric Data Types
Python has three main numeric data types:
- Integers (int): Integers are whole numbers, both positive and negative, without any decimal places. For example:
42,-17,0. - Floating-point Numbers (float): Floating-point numbers are used to represent decimal values. For example:
3.14,-2.5,0.0. - Complex Numbers (complex): Complex numbers are represented in the form
a + bj, whereais the real part andbis the imaginary part. For example:2 + 3j,-1 + 0j.
2. Boolean Data Type
The bool data type represents a logical value, which can be either True or False. Booleans are often used in conditional statements and logical operations.
3. Text Data Types
Python has two main text data types:
- Strings (str): Strings are sequences of characters, which can be enclosed in single quotes (
'), double quotes ("), or triple quotes ('''or"""). For example:"Hello, world!",'Python is fun',"""This is a multiline string.""". - Bytes and Byte Arrays (bytes, bytearray): These data types are used to represent binary data, such as images, audio, or other non-text data. For example:
b'Hello',bytearray([1, 2, 3]).
4. Sequence Data Types
Python has several sequence data types, which are used to store ordered collections of items:
- Lists (list): Lists are mutable (changeable) sequences of items, which can be of different data types. For example:
[1, 2, 3],['apple', 'banana', 'cherry']. - Tuples (tuple): Tuples are immutable (unchangeable) sequences of items, which can be of different data types. For example:
(1, 2, 3),('red', 'green', 'blue'). - Ranges (range): Ranges are used to represent a sequence of numbers. For example:
range(5)(0, 1, 2, 3, 4),range(1, 11, 2)(1, 3, 5, 7, 9).
5. Mapping Data Type
The Dictionary (dict) is the only mapping data type in Python. Dictionaries are unordered collections of key-value pairs, where each key must be unique. For example: {'name': 'John', 'age': 30, 'city': 'New York'}.
6. Set Data Types
Python has two set data types:
- Sets (set): Sets are unordered collections of unique elements. For example:
{1, 2, 3},{'apple', 'banana', 'cherry'}. - Frozen Sets (frozenset): Frozen sets are immutable (unchangeable) sets.
These are the main data types in Python, and they cover a wide range of use cases. Understanding these data types and their characteristics is essential for writing effective and efficient Python code.
