Python Basics (4): Learning and Examples of Basic Data Types

Python Basics (3): Examples and Descriptions of Basic Statements

1. Numeric type

In Python, common numeric types include integers (int), floating point numbers (float), and complex numbers (complex). The following are descriptions and examples of these numeric types:

1.1 Integer (int)

  • Represents an integer value with no fractional part.

  • Example:

    x = 10
    y = -5
    z = 0
    
  • Examples of Integer Operations

    
    x = 10
    y = 3
    
    print(x + y)    # 加法,输出 13
    print(x - y)    # 减法,输出 7
    print(x * y)    # 乘法,输出 30
    print(x / y)    # 除法,输出 3.3333333333333335
    print(x % y)    # 取模(取余),输出 1
    print(x // y)   # 整除,输出 3
    print(x ** y)   # 幂运算,输出 1000
    

insert image description here

1.2 floating point number (float)

  • Represents a numeric value with a fractional part.

  • Example:

    pi = 3.14
    temperature = 98.6
    
  • Example of floating point operations:

    pi = 3.14
    radius = 2.5
    
    print(2 * pi * radius)   # 计算圆的周长,输出 15.7
    print(pi * radius ** 2)  # 计算圆的面积,输出 19.625
    

insert image description here

1.3 Complex numbers

  • Represents a complex number with real and imaginary parts.

  • Example:

    z = 2 + 3j
    w = -1.5 + 0.5j
    
  • Examples of complex operations:

    # 复数示例
    z = 2 + 3j
    w = -1.5 + 0.5j
    
    print(z + w)   # 复数加法,输出 0.5 + 3.5j
    print(z * w)   # 复数乘法,输出 -3.5 + 1j
    print(z.conjugate())   # 求共轭复数,输出 2 - 3j
    

insert image description here

2. String type

In Python, a string (str) is a data type that represents text data. Strings consist of a sequence of characters enclosed in quotation marks (single or double). The following is an introduction and examples of the Python string type:

2.1 Definition of string

  • Strings can be enclosed in single or double quotes.
  • Example:
    message1 = 'Hello, world!'
    message2 = "Python is awesome!"
    

2.2 Escape characters

  • Escape characters are used to represent special characters in strings, usually beginning with a backslash (\).
  • Example:
    message = "She said, \"I'm fine.\""
    

The following is a table of commonly used escape characters and their descriptions in Python:

escape character describe
\' apostrophe
\" Double quotes
\\ backslash
\n new line
\t horizontal tab
\r carriage return
\b backspace
\f change page
\ooo Octal number, where ooois a 1-3 digit number
\xhh A hexadecimal number, where hhis a two-digit number

Special characters such as quotes, newlines, tabs, etc. can be represented in strings using escape characters. Here are some examples:

# 单引号和双引号
message1 = 'She said, \'Hello cxk!\''
message2 = "He said, \"Hi! cxk\""

# 换行和制表符
text = "Hello\n\tCxk!"

# 回车和退格
output = "Loading...\r100%"
text_with_backspace = "Hello\bCxk!"

# 八进制和十六进制
octal_char = "\101"    # 八进制数表示大写字母 "A"
hex_char = "\x41"      # 十六进制数表示大写字母 "A"

2.3 Multi-line strings

  • Multiline strings can be enclosed in triple quotes (three consecutive single or double quotes).
  • Example:
    poem = '''
    Roses are red,
    Violets are blue,
    Sugar is sweet,
    And so are you,
    kun is basketball.
    '''
    

2.4 String operations

  • Two strings can be concatenated using the plus sign (+).
  • Example:
    first_name = "蔡"
    last_name = "徐坤"
    full_name = first_name + " " + last_name
    

The following is a table of commonly used string operators in Python and their descriptions:

operator describe example
+ concatenates two strings 'Hello, ' + 'world!'
* repeat string 'Python' * 3
[] Get a single character in a string 'Hello'[0]
[x:y] Get a substring in a string 'Hello'[1:4]
in Determines whether a substring exists in a string 'world' in 'Hello, world!'
not in Check if a substring does not exist in a string 'Alice' not in 'Hello, Bob'

Example:

greeting = 'Hello, '
name = '徐州蔡徐坤'

# 连接两个字符串
message = greeting + name
print(message)     # 输出: Hello, cxk

# 重复字符串
line = '-' * 10
print(line)        # 输出: ----------

# 获取单个字符
first_char = name[0]
print(first_char)  # 输出: A

# 获取子串
substring = name[1:4]
print(substring)   # 输出: lic

# 判断子串是否存在
is_contained = '坤' in greeting
print(is_contained)   # 输出: False

# 判断子串是否不存在
is_not_contained = '坤' not in greeting
print(is_not_contained)   # 输出: True

insert image description here

2.5 String Formatting

  • Using the placeholder and formatting methods, the value of a variable can be inserted into a string.
  • Example:
    name = "CXK"
    age = 25
    message = "My name is {} and I'm {} years old.".format(name, age)
    

3. List type

In Python, a list (List) is a 有序、可变data type used to store and manipulate multiple elements. Lists support adding, inserting, and deleting elements, as well as accessing and modifying elements by index. Lists are denoted using square brackets ([]), with elements separated by 逗号.

The following is an introduction and examples of Python list types:

3.1 Definition of list

  • A list is a collection of elements arranged in a specific order.
  • Example:
    numbers = [1, 2, 3, 4, 5]
    names = ['Ai', 'book', 'chris']
    

3.2 Accessing List Elements

  • An index can be used to access a specific element in a list. The index starts from 0the beginning, and the negative index means 末尾counting down from the beginning.
  • Example:
    numbers = [1, 2, 3, 4, 5]
    
    print(numbers[0])     # 输出: 1
    print(numbers[-1])    # 输出: 5
    

3.3 Modify list elements

  • The elements in the list can be modified by indexing.
  • Example:
    numbers = [1, 2, 3, 4, 5]
    
    numbers[0] = 10
    print(numbers)    # 输出: [10, 2, 3, 4, 5]
    

3.4 List operations

  • Lists support various operations such as adding elements, removing elements, slicing, etc.
  • Example:
       players = ['kobe', 'jordan', 'Lin']
       
       players.append('wade')  # 添加元素到列表末尾
       print(players)  # 输出:['kobe', 'jordan', 'Lin', 'wade']
       
       players.insert(1, 'curry')  # 在指定位置插入元素
       print(players)  # 输出: ['kobe', 'curry', 'jordan', 'Lin', 'wade']
       
       del players[2]  # 删除指定位置的元素
       print(players)  # 输出: ['kobe', 'curry', 'Lin', 'wade']
       
       players_slice = players[1:3]  # 切片操作,获取子列表
       print(players_slice)  # 输出:['curry', 'Lin']
    

insert image description here

3.5 List length and traversal

  • You can use the built-in function len()to get the length of the list, and use a loop to iterate over the elements in the list.
  • Example:
       players = ['kobe', 'jordan', 'Lin', 'rose']
       
       print(len(players))  # 输出: 4
       for player in players:
          print(player)  # 依次输出:kobe,jordan,Lin,rose
    

insert image description here

4. Tuple type

In Python, a tuple (Tuple) is a 有序的、不可变data type used to store multiple elements. Since tuples are immutable, they can be used in scenarios where immutable collections of data need to be stored. Tuples are represented using parentheses ( ( ) ), with elements separated by 逗号.

Here is an introduction and example of the Python tuple type:

4.1 Definition of tuple

  • A tuple is a collection of elements arranged in a specific order, similar to a list, but a tuple is immutable, that is, it cannot be modified after creation.
  • Example:
    point = (2, 3)
    colors = ('red', 'green', 'blue')
    

4.2 Accessing tuple elements

  • An index can be used to access a specific element in a tuple. The index starts from 0, and the negative index means counting down from the end.
  • Example:
    point = (2, 3)
    
    print(point[0])     # 输出: 2
    print(point[-1])    # 输出: 3
    

4.3 Properties of tuples

  • Tuples are immutable, i.e. the elements in the tuple cannot be modified after creation.
  • Example:
    point = (2, 3)
    
    # 尝试修改元组中的元素,将会抛出错误
    point[0] = 10
    
    insert image description here

4.4 Unpacking of tuples

  • The elements of a tuple can be unpacked into multiple variables.
  • Example:
    point = (2, 3)
    x, y = point
    
    print(x)    # 输出: 2
    print(y)    # 输出: 3
    

4.5 Applications of tuples

  • Tuples can be used in scenarios such as assignment of multiple variables, functions returning multiple values, etc.
  • Example:
    # 多个变量的赋值
    x, y, z = 1, 2, 3
    
    # 函数返回多个值
    def get_point():
        return 2, 3
    
    x, y = get_point()
    

5. Collection type

In Python, a set (Set) is a 无序、不重复data type used to store multiple unique elements. It supports 添加、删除element-wise and equal- 交集、并集set operations, making it ideal for processing 唯一性的collections that require data. Collections are represented using curly braces ({}), with elements separated by commas.

The following is an introduction and examples of Python collection types:

5.1 Definition of collection

  • A set is a collection of unique, unordered elements.
  • Example:
    fruits = {
          
          'apple', 'banana', 'cherry'}
    

5.2 Create a collection

  • Collections can be created using 花括号or .内置函数 set()
  • Example:
    # 使用花括号创建集合
    fruits = {
          
          'apple', 'banana', 'cherry'}
    
    # 使用set()函数创建集合
    numbers = set([1, 2, 3, 4, 5])
    

5.3 Accessing Collection Elements

  • Since the collection is unordered, the elements in the collection cannot be accessed through the index, only whether the element exists in the collection can be judged.
  • Example:
    fruits = {
          
          'apple', 'banana', 'cherry'}
    
    if 'apple' in fruits:
        print("苹果在集合中")
    

5.4 Collection operations

  • Sets support various operations, such as adding elements, removing elements, intersecting sets, and unions, etc.
  • Example:
    fruits = {
          
          'apple', 'banana', 'cherry'}
    
    fruits.add('orange')         # 添加元素到集合
    print(fruits)                # 输出: {'apple', 'banana', 'cherry', 'orange'}
    
    fruits.remove('banana')      # 删除指定元素
    print(fruits)                # 输出: {'apple', 'cherry', 'orange'}
    
    numbers1 = {
          
          1, 2, 3, 4}
    numbers2 = {
          
          3, 4, 5, 6}
    
    intersection = numbers1 & numbers2   # 求交集
    print(intersection)          # 输出: {3, 4}
    
    union = numbers1 | numbers2  # 求并集
    print(union)                 # 输出: {1, 2, 3, 4, 5, 6}
    

5.5 Properties of collections

  • The elements in the collection are 唯一yes, there will be no duplicate elements.
  • Collections are 可变, yes, 添加和删除elements.
  • Sets Yes 无序, the elements are in no particular order.
  • Example:
    fruits = {
          
          'apple', 'banana', 'cherry', 'apple'}
    print(fruits)    # 输出: {'apple', 'banana', 'cherry'}
    

6. Dictionary type

In Python, a dictionary (Dictionary) is a 无序的、可变data type used for 存储键值对(key-value pairs). It supports pass through 键访问值、添加和删除键值对, and get all keys and values ​​operations. Dictionaries 快速查找、关联和索引are very convenient when dealing with the data
you need. Dictionaries are represented by curly braces ({}), each key-value pair is separated by a colon (:), and the key and value are separated by a comma.

The following is an introduction and example of the Python dictionary type:

6.1 Dictionary definition

  • A dictionary is a 无序的、键值对collection that 一个键和对应的值consists of each key-value pair.
  • Example:
    person = {
          
          'name': 'Alice', 'age': 25, 'city': 'New York'}
    

6.2 Accessing dictionary elements

  • You can use the keys to access the values ​​in the dictionary.
  • Example:
    person = {
          
          'name': 'Alice', 'age': 25, 'city': 'New York'}
    
    print(person['name'])    # 输出: Alice
    print(person['age'])     # 输出: 25
    

6.3 Modify dictionary elements

  • Values ​​in the dictionary can be modified by key.
  • Example:
    person = {
          
          'name': 'Alice', 'age': 25, 'city': 'New York'}
    
    person['age'] = 26
    print(person)    # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York'}
    

6.4 Dictionary operations

  • Dictionaries support various operations such as adding key-value pairs, removing key-value pairs, getting all keys and values, etc.
  • Example:
    person = {
          
          'name': 'Alice', 'age': 25, 'city': 'New York'}
    
    person['gender'] = 'Female'     # 添加键值对
    print(person)                   # 输出: {'name': 'Alice', 'age': 25, 'city': 'New York', 'gender': 'Female'}
    
    del person['age']               # 删除键值对
    print(person)                   # 输出: {'name': 'Alice', 'city': 'New York'}
    
    keys = person.keys()            # 获取所有键
    print(keys)                     # 输出: dict_keys(['name', 'city'])
    
    values = person.values()        # 获取所有值
    print(values)                   # 输出: dict_values(['Alice', 'New York'])
    

6.5 Properties of dictionaries

  • The keys in the dictionary are yes 唯一, there will be no duplicate keys.
  • Dictionaries Yes 可变, key-value pairs can be added, modified and deleted.
  • Dictionaries Yes 无序, there is no particular order between keys and values.
  • Example:
    person = {
          
          'name': 'Alice', 'age': 25, 'city': 'New York', 'name': 'Bob'}
    print(person)    # 输出: {'name': 'Bob', 'age': 25, 'city': 'New York'}
    

7. Boolean type

In Python, the Boolean type is a represented 真(True)和假(False)data type. The boolean type 条件判断和逻辑运算plays a key role in and can help us perform operations based on different conditions 分支控制和逻辑判断. When writing programs, Boolean types are often used for conditional judgment and logic operations in order to achieve different behaviors and control processes.

The following is an introduction and example of the Python Boolean type:

7.1 Definition of Boolean type

  • The Boolean type has only two values, namely True (true) and False (false).
  • Example:
    is_true = True
    is_false = False
    

7.2 Boolean operations

  • The Boolean type supports logical operators (and, or, not) and comparison operators (==, !=, <, >, <=, >=).
  • Example:
    x = 5
    y = 10
    
    result1 = x > 3 and y < 15   # and逻辑运算
    print(result1)              # 输出: True
    
    result2 = x < 3 or y > 15    # or逻辑运算
    print(result2)              # 输出: False
    
    result3 = not(x > 3)         # not逻辑运算
    print(result3)              # 输出: False
    
    result4 = x == 5             # 相等比较
    print(result4)              # 输出: True
    
    result5 = x != 5             # 不等比较
    print(result5)              # 输出: False
    

7.3 Application of Boolean type

  • The Boolean type is usually used for conditional judgments, such as in control structures such as if statements and while loops.
  • Example:
    x = 5
    
    if x > 0:
        print("x是正数")       # 输出: x是正数
    
    is_even = x % 2 == 0
    
    if is_even:
        print("x是偶数")
    else:
        print("x是奇数")       # 输出: x是奇数
    

8. None type

In Python, None is a special constant that represents a null or missing value. It is Python's null object, which means an object that does not exist or has no value.

The following is an introduction and example of the None type in Python:

8.1 Definition of None type

  • The None type represents a null or missing value and is used to represent an object with no value.
  • Example:
    x = None
    

8.2. Characteristics of the None type

  • None is one 常量, it is not an instance of any data type.
  • Yes, the None object is 唯一immutable.
  • The None type 条件判断、函数返回值is often used to represent situations in scenarios such as 没有有效值.
  • Example:
    def find_max(numbers):
        if len(numbers) == 0:
            return None
        
        max_value = numbers[0]
        for num in numbers:
            if num > max_value:
                max_value = num
        
        return max_value
    
    numbers = [1, 2, 3, 4, 5]
    max_num = find_max(numbers)
    
    if max_num is None:
        print("列表为空")
    else:
        print("最大值为:", max_num)
    

9. Enumerated types

In Python, enumeration (Enumeration) is a method for 定义常量集合的数据类型. Enumerated types provide a more readable and maintainable way to represent a fixed set of values.

Enumerated types in Python are enumprovided by modules, which Python 3.4have been part of the standard library since version 2. The following is an introduction and examples of enumerated types:

9.1 Defining enumerated types

Enumeration types can enum.Enumbe defined by inheriting classes, and each enumeration constant is an instance object of this class.

Example one:

import enum

class Color(enum.Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

Example 2: Define an enumeration type using a decorator

import enum

@enum.unique
class Weekday(enum.Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

9.2 Using enumerated types

Enumeration constants can be accessed through the enumeration type, and enumeration constants can be compared and iterated over.

Example 1: Accessing enumeration constants

# 访问枚举常量
print(Color.RED)  # 输出: Color.RED
print(Color.RED.value)  # 输出: 1

Example 2: Comparing enumeration constants

# 比较枚举常量
color1 = Color.RED
color2 = Color.BLUE
print(color1 == color2)  # 输出: False

Example 3: Iterating over enumeration constants

# 迭代枚举常量
for color in Color:
    print(color)
# 输出:
# Color.RED
# Color.GREEN
# Color.BLUE

9.3 Other features of enumerations

Enumerated types also provide some other useful features such as auto-assignment, custom values, name access, etc.

Example 1: Automatic assignment

import enum

class Color(enum.Enum):
    RED  # 自动赋值为1
    GREEN  # 自动赋值为2
    BLUE  # 自动赋值为3

print(Color.RED.value)  # 输出: 1

Example 2: Custom Values

import enum

class Color(enum.Enum):
    RED = 100
    GREEN = 200
    BLUE = 300

print(Color.RED.value)  # 输出: 100

Example 3: Accessing enumeration constants by name

import enum

class Color(enum.Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Color['RED'])  # 输出: Color

.RED

Guess you like

Origin blog.csdn.net/qq_29864051/article/details/131344315