In-depth understanding of Python data types and applications

Python provides a rich set of built-in data types that enable you to handle different types of data in your program. Core numeric types include integers, floating point numbers, and complex numbers. Integer represents whole numbers and is useful for precise counting and calculations.

Floating point numbers represent real numbers with decimal precision, which is important for scientific and statistical calculations. Complex numbers extend numbers into the complex plane and are used in many scientific and mathematical applications.

Python has many built-in data types that enable you to store and manipulate data in powerful ways. Choosing appropriate data types is very important for writing efficient Python code. This comprehensive guide will provide a detailed introduction to various Python data types through code examples.

Numeric type

Numeric data types in Python allow you to handle numeric data such as integers, floating point numbers, and complex numbers. Let's look at each numeric type one by one.

Integer(int)

Integers are whole numbers such as -2, -1, 0, 1, 2, 3, etc. They can be positive, negative or 0. In Python, integers are immutable. Some examples: 

x = 10    # positive integer
y = -5    # negative integer 
print(type(x)) # <class 'int'>

We can perform mathematical operations on integers such as addition, subtraction, multiplication etc. 

a = 12
b = 4
print(a + b) # 16
print(a - b) # 8
print(a * b) # 48

Integers can be converted to other types such as floats, complex numbers, etc. 

num = 10
print(type(num)) # <class 'int'> 
num2 = float(num)
print(type(num2)) # <class 'float'>

floating point number (float)

Floating point numbers represent real numbers, such as -1.5, -0.4, 0.0, 1.25, 9.8, etc. They contain decimal points. Very useful in scientific and statistical calculations where precision is required. Some examples:

a = 1.5
b = -0.4
print(type(a)) # <class 'float'>

Floating point numbers support mathematical operations such as addition, subtraction, etc.

x = 3.0
y = 5.5 
print(x + y) # 8.5
print(x - y) # -2.5 
print(x * y) # 16.5

They can be converted to other types such as int, complex, etc.

a = 1.2
print(type(a)) # <class 'float'>
b = int(a) 
print(type(b)) # <class 'int'>

plural

Complex numbers are written in the form x + yj, where x is the real part and y is the imaginary part. They are very useful in scientific and mathematical applications.

x = 5 + 3j
print(type(x)) # <class 'complex'>

We can perform operations such as addition and multiplication on complex numbers.

a = 2+3j
b = 5+4j
print(a + b) # 7+7j 
print(a * b) # -7+26j

They can be converted to other types such as int, float, etc.

x = 5 + 3j
print(type(x)) # <class 'complex'>
y = float(x)
print(type(y)) # <class 'float'>

Boolean type

The Boolean type represents the logical values ​​True and False. Used for conditional testing and logic. For example:

x = True
y = False
print(type(x)) # <class 'bool'>

Logical expressions and conditions can be combined using Boolean operators such as and, or, and not.

a = True
b = False
print(a and b) # False 
print(a or b) # True
print(not a) # False

Other data types can be converted to Boolean values ​​based on their truth values.

x = 5
print(bool(x)) # True 
y = 0
print(bool(y)) # False

sequence type

Sequence types allow collections of data to be stored in an ordered manner. Let’s learn about them one by one:

string(str)

A string represents a sequence of Unicode characters, such as letters, numbers, spaces, etc. In Python they are immutable. Some examples of creating strings:

s1 = 'Hello'
s2 = "World"
print(type(s1)) # <class 'str'>

We can access individual characters using indexing:

s = 'python'
print(s[0]) # p
print(s[3]) # h

Strings support operations such as concatenation, slicing, length, etc.

s1 = 'Hello'
s2 = 'World'
print(s1 + ' ' + s2) # Hello World
print(len(s1)) # 5

Format specifiers such as %s can be used for formatting:

name = 'John'
print('My name is %s' % name) # My name is John

list

A list is an ordered collection of values ​​that is mutable (modifiable). Allows storage of different data types.

nums = [1, 2, 3]
fruits = ['apple', 'mango', 'banana']
print(type(nums)) # <class 'list'>

We can access elements using indexes. Lists are mutable.

nums[0] = 5 
print(nums) # [5, 2, 3]

Lists support operations such as concatenation, slicing, length, etc.

fruits = ['apple', 'banana', 'mango']
print(len(fruits)) # 3
print(fruits[1:]) # ['banana', 'mango']

tuple

Tuples are ordered collections of values ​​that are immutable (cannot be modified). Allows storage of different data types.

point = (2, 3) # 括号不是必需的,但建议使用
colors = ('red', 'blue', 'green')
print(type(point)) # <class 'tuple'>

We can access elements using indexes, but we cannot modify tuples.

point[0] = 5 #错误:无法修改元组

Tuples support operations such as concatenation, slicing, length, etc.

colors = ('red', 'blue', 'green')
print(len(colors)) # 3
print(colors[1:]) # ('blue', 'green')

Range

range represents an immutable sequence of numbers. Typically used to loop through a sequence of numbers.

nums = range(5) # 0到4
print(list(nums)) # [0, 1, 2, 3, 4]

range is often used in for loops:

for i in range(3):
    print(i)
# 输出:
# 0
# 1
# 2

We can also create a range with a start, end and step size.

nums = range(3, 8, 2)
print(list(nums)) # [3, 5, 7]

Collection type

A set is an unordered collection of unique values. They support operations such as membership testing, set mathematics, and more.

gather

The collection contains only unique values. Elements can be added and removed.

colors = {'red', 'blue', 'green'}
print(type(colors)) # <class 'set'>

Collection elements can be tested for membership and added/removed. Collections are mutable.

'red' in colors # True
colors.add('yellow')
colors.remove('blue')

Set mathematical operations such as union and intersection can be performed between sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # {1, 2, 3, 4, 5}
print(set1 & set2) # {3}

immutable collection

Immutable collections are an immutable variant of Python collections. Elements cannot be added or removed.

colors = frozenset(['red', 'blue', 'green'])
print(type(colors)) # <class 'frozenset'>
colors.add('yellow') # AttributeError

Immutable collections can be used as dictionary keys as well as set operations.

Mapping type

Map types allow data to be stored as key-value pairs. Dictionaries are the main mapping type in Python.

dictionary

A dictionary consists of key-value pairs, enclosed in curly braces {}. Used to store related data.

student = {
    'name': 'John',
    'age': 20,
    'courses': ['Math', 'Science']
}
print(type(student)) # <class 'dict'>

Dictionary elements can be accessed by key and modified. Dictionaries are mutable.

student['name'] = 'Mark' # 更新值
print(student['courses']) # ['Math', 'Science']

Common dictionary operations include length, adding/removing keys, iteration, etc.

print(len(student)) # 3
student['email'] = '[email protected]' # 添加键值
for key in student:
    print(key, student[key]) # 打印每个项

binary type

The binary type in Python is used to handle binary data such as bytes, byte arrays, etc.

byte

Bytes represent an immutable sequence of bytes. Example:

data = b'hello'
print(type(data)) # <class 'bytes'>

Bytes support operations such as indexing, length, concatenation, etc., but they are immutable.

print(data[0]) # 104
print(len(data)) # 5
data2 = data + b'world' # 无法修改,只能连接

byte array

A byte array represents a variable sequence of bytes. They can be modified in place.

data = bytearray(b'hello')
print(type(data)) # <class 'bytearray'>
data[0] = 106 # 可变的

Byte arrays support typical sequence operations such as indexing, joining, etc.

print(data[0]) # 106
data2 = data + bytearray(b'world')

Memoryview

Memoryview objects allow direct access to the internal data of objects that support the buffer protocol without the need for copying. For advanced optimization.

data = memoryview(b'hello')
print(data[0]) # 104

Memoryview supports slicing and editing without copying buffers. Advanced usage for performance.

data[1:4] = b'i' # 在原地编辑
print(data) # b'hiello'

None Type

The None type represents a missing value. Similar to null in other languages.

x = None
print(type(x)) # <class 'NoneType'>

None is often used as a placeholder for optional or missing values.

def print_if_not_none(x):
    if x is None:
        print('x is None')
    else:
        print(x)

Operator can check if something is None.

x = None
print(x is None) # True

In short, Python comes with a variety of built-in data types, including numeric values, text, sets, maps, and more. Choosing the appropriate data type helps to use memory efficiently and improve performance. Manipulating data types is an important part of Python programming.

Hopefully this overview has given you a good understanding of the different data types available in Python, along with numerous code examples demonstrating their use.

·  END  ·

HAPPY LIFE

7937e6b02f33990d6583a6a939feda40.png

This article is for learning and communication only. If there is any infringement, please contact the author to delete it.

Guess you like

Origin blog.csdn.net/weixin_38739735/article/details/132930249