Python code todo comments, folder naming conventions, and bit operation principles

Table of Contents

Summary and supplement of day08 knowledge points

1. Knowledge summary

1.1 Name

1.2 Notes

1.3 todo

1.4 Conditional nesting

1.5 Simple logic is dealt with first

1.6 Loop

1.7 Variables and values

2. Knowledge supplement

2.1 pass

2.2 is comparison

2.3 Bit operations

3. Stage summary (mind map version)


Summary and supplement of day08 knowledge points

1. Knowledge summary

1.1 name

During the Python development process, folders/files/variables, etc. will be created, and there are some unspoken rules for naming these (you should also pay attention to the pep8 specification when writing code).

  • Folders, lowercase & amp; lowercase underscore connections, for example: commands, data_utils, etc.

  • File, lowercase & amp; lowercase underscore connection, for example: page.py, db_convert.py, etc.

  • variable

    • Global variables, uppercase & amp; connected by uppercase underscores, for example: NAME = "Big Shaobing", BASE_NAME = 18

    • Local variables, lowercase & amp; lowercase and underscore connections, for example: data = [11,22,33], user_parent_id = 9, etc.

1.2 Comment

As a programmer, writing code comments is a very basic and useful skill to facilitate the maintenance and understanding of the code in the future.

  • folder

  • File comments

“””
This file mainly provides tools and conversion functions for the project, in addition to logs….
For example:



“””

  • Code comments
name = "Big Smart"
# Add a big sesame seed cake after the name
data = name + "dsb"
print(data)
name = "Big Smart"
"""
Add a big sesame seed cake after the name, the internal implementation mechanism:
1.xxx
    2.xxx
    3.xx
"""
data = name + "dsb"
print(data)

1.3 todo

1.4 Conditional Nesting

In the future, when writing conditional statements, you must find ways to reduce the nesting level (preferably no more than 3 levels).

1.5 Simple logic is processed first

Example 1:

goods = [
    {"name": "computer", "price": 1999},
    {"name": "mouse", "price": 10},
    {"name": "yacht", "price": 20},
    {"name": "Beauty", "price": 998}
]
for index in range(len(goods)):
    item = goods[index]
    print(index + 1, item['name'], item['price'])
?
while True:
    num = input("Please enter the product serial number (Q/q) to be selected:") # "1"
    if num.upper() == "Q":
        break
    if num.isdecimal():
        num = int(num)
        if 0 < num < 5:
            target_index = num - 1
            choice_item = goods[target_index]
            print(choice_item["name"], choice_item['price'])
        else:
            print("Wrong selection of serial number range")
    else:
        print("The serial number entered by the user is in an incorrect format")

Example 2:

goods = [
    {"name": "computer", "price": 1999},
    {"name": "mouse", "price": 10},
    {"name": "yacht", "price": 20},
    {"name": "Beauty", "price": 998}
]
for index in range(len(goods)):
    item = goods[index]
    print(index + 1, item['name'], item['price'])
?
while True:
    num = input("Please enter the product serial number (Q/q) to be selected:") # "1"
    if num.upper() == "Q":
        break
    if not num.isdecimal():
        print("The input format is wrong")
        break
    num = int(num)
?
    if num > 4 or num < 0:
        print("Range selection error")
        break
    target_index = num - 1
    choice_item = goods[target_index]
    print(choice_item["name"], choice_item['price'])

1.6 Loop

Try to do as few loops as possible and do more to improve code efficiency.

key_list = []
value_list = []
?
info = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
?
for key, value in info.items():
    key_list.append(key)
    value_list.append(value)
info = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
?
key_list = list(info.keys())
value_list = list(info.values())

1.7 Variables and Values

# Recommended
name = "Big Shaobing"
age=19
# Not recommended
name="Big Shaobing"
age= 18

Automatic processing can be achieved based on Pycharm’s formatting tool.

  1. (windows shortcut key: Ctrl + Alt + L)
  2. (Mac shortcut key: command + option + L)

Python code specifications: refer to the PEP8 specification.

2. Knowledge supplement

2.1 pass

Generally, Python code blocks are implemented based on : and Indentation. Python stipulates that the code block must have code to be complete. In order to ensure that there is no code The completeness of the syntax can be replaced by pass, for example:

# Other programming languages
if submit{
    ...
}else{
    ....
}
#python
if condition:
    pass
else:
    pass



for i in range(xxx):
    pass

2.2 is compare

What is the difference between is and ==?

  • ==, used to compare whether two values are equal.

  • is is used to indicate whether the memory addresses are consistent.

# Example 1
v1 = []
v2 = []
?
print( v1 == v2 ) # True, the two values are equivalent
print( v1 is v2 ) # False, do not belong to the same memory. 
# Example 2
v1 = []
v2 = v1
?
print( v1 == v2 ) # True, the two values are equivalent
print( v1 is v2 ) # True, belongs to the same memory. 
# Example 3
v1 = None
v2 = None
?
print(v1 == v2) # True, the two values are equivalent
print(v1 is v2) # True, belongs to the same memory. 

2.3-bit operation

The bottom layer of computers is essentially binary. Many operations we usually do in computers will be converted into binary operations at the bottom layer. Bit operations are binary operations.

  • & amp;, and (both 1)

    a = 60 # 60 = 0011 1100
    b = 13 # 13 = 0000 1101
    ?
    c = a & b # 12 = 0000 1100
  • |, or (as long as one is 1)

    a = 60 # 60 = 0011 1100
    b = 13 # 13 = 0000 1101
    ?
    c = a | b # 61 = 0011 1101 
  • ^, XOR (different values)

    a = 60 # 60 = 0011 1100
    b = 13 # 13 = 0000 1101
    ?
    c = a ^ b # 49 = 0011 0001 
  • ~, negate

    a = 60 # 60 = 0011 1100
    ?
    c = ~a; # -61 = 1100 0011
  • <<, move left

    a = 60 # 60 = 0011 1100
    c = a << 2; # 240 = 1111 0000
  • >>, move right

    a = 60 # 60 = 0011 1101
    c = a >> 2; # 15 = 0000 1111

In normal development, binary bit operations are rarely used. They are used more at the bottom of the computer or the bottom of the network protocol, for example:

  • Calculate 2**n

    2**0 1 << 0 1 1
    2**1 1 << 1 10 2
    2**2 1 << 2 100 4
    2**3 1 << 3 1000 8
    ...
  • Calculate half of a number [Interview Question]

    v1 = 10 >> 1
    print(v1) #The value is 5
    ?
    v2 = 20 >> 1
    print(v2) #The value is 10
  • When transmitting data over the network, the file is too large and has not been completely transferred (websocket source code is an example).

     1st byte 2nd byte ...
     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
     + - + - + - + - + ------- + - + ---------------- + ----------------- --------------- +
    |F|R|R|R| opcode|M| Payload len | Extended payload length |
    |I|S|S|S| (4) |A| (7) | (16/64) |
    |N|V|V|V| |S| | (if payload len==126/127) |
    | |1|2|3| |K| | |
     + - + - + - + - + ------- + - + ------------- + - - - - - - - - - - - - - - - +
    ?
    The FIN position is 0, indicating that this is part of the data, and there will be data to follow.
    The FIN position is 1, indicating that this is the last data and has been sent. 
    # For example: the value of the first byte received is 245 (11110101), let the binary sum of v 1000 0000 do & amp; AND operation.
    ?
    v = 245 # 245 11110101
              # 128 10000000
                    10000000
        
    data = v & 128
    if data == 0:
        print("There is still data")
    else:
        print("Completed")

3. Stage summary (mind map version)

You can use mind maps (xmind software) to sort out the content of knowledge points at each stage, and write out the summary and key points of the knowledge, which will also facilitate future review and review.