我的 Python 代码中的缩进问题在哪里?

Where is indentation problem in my Python code?

提问人:ramizzik 提问时间:11/22/2022 最后编辑:ramizzik 更新时间:11/22/2022 访问量:42

问:

我正在尝试解决我的家庭作业编码作业,但我的代码中出现缩进错误。我现在花了很长时间试图弄清楚我做错了什么,但我没有看到错误。此外,我的一个朋友有一个非常相似的代码,它对他来说很好用。

添加第 141 行和第 142 行后引发缩进错误。 在 main() 函数中以单词“with”开头。点击查看图片 -> 缩进错误行 141、142

我还尝试将该功能放在单独的函数中,当我尝试在main()中调用它时,我遇到了同样的错误。完整代码附在下面。

感谢社区!

`

#Imports
import sys
import os
from bitstring import BitArray

#Declaration of variables
op = ''
rt = ''
rs = ''
imm = ''
ans = ''
shamt = ''
funct = ''
comm = ''
RegDst = ''
ALUSrc = ''
MemtoReg = ''
RegWrite = ''
MemRead = ''
MemWrite = ''
branch = ''
ALUOp1 = ''
ALUOp2 = ''
zeroBit = ''
oper = ''

#Dictionaries
opDict = {'001000' : 'addi', '000000' : {'100000' : 'add', '100010' : 'sub'}}
regValues = [0, 0, 0, 0, 0, 0, 0, 0]
regMap = {'00000' : 0 , '00001' : 1, '00010' : 2, '00011' : 3, '00100' : 4, '00101' : 5, '00110' : 6, '00111' : 7}


#Main function

        
def program(request, newFile, newFileTwo, count):
    splitInput(request, newFile)
    ans = str(regValues).replace(",", "")
    ans = ans.replace("[","")
    ans = ans.replace("]","")
    ans = ans.replace(" ","|")  
    newFileTwo.write(str(count) + "|" + ans + '\n')

#Utility functions
def splitInput(inn, file):
    op = inn[0:6]
    if (op == '001000'):
        # I-Type
        rt = inn[6:11]
        rs = inn[11:16]
        imm = inn[16:32]
        b = BitArray(bin=imm)
        ans = b.int
        oper = 'addi'
        decideCtrl(oper, file)
        addi(rt, rs, ans)
    elif (op == '000000'):
        # R - Type
        rs = inn[6:11]
        rt = inn[11:16]
        rd = inn[16:21]
        shamt = inn[21:26]
        funct = inn[26:33].replace("\n", "")
        # Add / Sub
        if(opDict['000000'][funct] == 'add'):
            # Add command
            oper = 'add'
            decideCtrl(oper, file)
            add(rs,rt,rd)
        elif(opDict['000000'][funct] == 'sub'):
            # Sub Command
            oper = 'sub'
            decideCtrl(oper, file)
            sub(rd, rs, rt)

 
#Dedice on control signals
def decideCtrl(op, file):
    match op:
        case 'add':
            RegDst = '1'
            RegWrite = '1'
            ALUSrc = '0'
            MemtoReg = '0'
            RegWrite = '1'
            MemRead = '0'
            MemWrite = '0'
            branch = '0'
            ALUOp1 = '1'
            ALUOp2 = '0'
            comm = 'add'
            file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite + branch + ALUOp1 + ALUOp2 +'\n')
        case 'sub':
            RegDst = '1'
            RegWrite = '1'
            ALUSrc = '0'
            MemtoReg = '0'
            RegWrite = '1'
            MemRead = '0'
            MemWrite = '0'
            branch = '0'
            ALUOp1 = '1'
            ALUOp2 = '0'
            comm = 'sub'
            file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite + branch + ALUOp1 + ALUOp2 + '\n')
        case 'addi':
            RegDst = '0'
            RegWrite = '1'
            ALUSrc = '1'
            MemtoReg = '0'
            RegWrite = '1'
            MemRead = '0'
            MemWrite = '0'
            branch = '0'
            ALUOp1 = '0'
            ALUOp2 = '0'
            comm = 'addi'
            file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite + branch + ALUOp1 + ALUOp2 + '\n')

#Commands
def add(rs, rt, rd):
    regValues[regMap[rd]] = regValues[regMap[rs]] + regValues[regMap[rt]]

def sub(rd, rs, rt):
    regValues[regMap[rd]] = regValues[regMap[rs]] - regValues[regMap[rt]]

def addi(rt, rs, imm):
    regValues[regMap[rs]] = regValues[regMap[rt]] + imm
    
   

def main():
    PCount = 65536
    count = 0
    # inputName = str(sys.argv[1])
    # F = open(inputName, "r")

    with open(filename, "r") as file:
        storedLines = file.read().splitlines()

    newFile = open("outputOne.txt", "w")
    newFileTwo = open("outputTwo.txt", "w")

    
    
    ans = str(regValues).replace(",", "")
    ans = ans.replace("[","")
    ans = ans.replace("]","")
    ans = ans.replace(" ","|")  
    newFileTwo.write(str(PCount) + "|" + ans + '\n')
    
    # for comms in F:
    #   if (count == 100):
    #       F.close()
    #       newFile.close()
    #       newFileTwo.close()
    #       exit()
    #   PCount = PCount + 4
    #   program(comms, newFile, newFileTwo, PCount)
    #   count = count + 1


    
    #F.close()
    newFile.close()
    newFileTwo.close()  


# Use open file to store the lines with their indicies
# When beq or bne compare and if it's true -> grab the label imm -> convert to decimal
# -> divide by 4 to get actual line

# Ad

# While i less than size of array of lines go one by one and do logic
#   storedLines[i] - line of a code in a file. Do logic to each [i]
# Add internal pc counter (intpc=0). By each iteration of i intpc goes +4
# at the end  of while loop internalPC = 4
# i == internalPC // 4

# App Entry Point
if __name__ == "__main__":
    main()

`

  • 将我的代码与朋友的代码进行比较,看起来它对他有用(相同的行,141、142)
  • 试图将功能放在单独的函数中 -> 不起作用
  • 我希望代码使用
python 语法-错误 缩进pylance

评论

1赞 Samwise 11/22/2022
很可能是制表符与空格的东西。确保您在整个函数中始终使用相同类型的缩进。(您可以将 IDE 配置为在保存时自动规范化它们,这样可以完全避免此类问题。

答:

0赞 Ingwersen_erik 11/22/2022 #1

我修复了在您的代码中发现的缩进错误,对其进行了一些更改,并添加了一些注释注释:"# NOTE: ..."


# == Necessary Imports =========================================================
import sys
import os

from bitstring import BitArray


# == Variables =================================================================
op = ""
rt = ""
rs = ""
imm = ""
ans = ""
shamt = ""
funct = ""
comm = ""
RegDst = ""
ALUSrc = ""
MemtoReg = ""
RegWrite = ""
MemRead = ""
MemWrite = ""
branch = ""
ALUOp1 = ""
ALUOp2 = ""
zeroBit = ""
oper = ""

# == Dictionaries ==============================================================
opDict = {"001000": "addi", "000000": {"100000": "add", "100010": "sub"}}
regValues = [0, 0, 0, 0, 0, 0, 0, 0]
regMap = {
    "00000": 0,
    "00001": 1,
    "00010": 2,
    "00011": 3,
    "00100": 4,
    "00101": 5,
    "00110": 6,
    "00111": 7,
}


# == Main Function =============================================================
def program(request, newFile, newFileTwo, count):
    splitInput(request, newFile)
    ans = (
        str(count)
        + "|"
        + str(regValues)
        .replace(",", "")
        .replace("[", "")
        .replace("]", "")
        .replace(" ", "|")
        + "\n"
    )
    newFileTwo.write(ans)


# == Utility Function ==========================================================
def splitInput(inn, file):
    op = inn[:6]
    if op == "000000":
        # R-Type
        rs = inn[6:11]
        rt = inn[11:16]
        rd = inn[16:21]
        # NOTE: `shamt` shadows the global variable `shamt`.
        shamt = inn[21:26]
        # NOTE: `funct` shadows the global variable `funct`.
        funct = inn[26:33].replace("\n", "")

        # Add / Sub
        if opDict["000000"][funct] == "add":
            decideCtrl("add", file)
            add(rs, rt, rd)
        elif opDict["000000"][funct] == "sub":
            decideCtrl("sub", file)
            sub(rd, rs, rt)

    elif op == "001000":
        # I-Type
        # NOTE: `rt` shadows the global variable `rt`.
        rt = inn[6:11]
        # NOTE: `rs` shadows the global variable `rs`.
        rs = inn[11:16]
        # NOTE: `imm` shadows the global variable `imm`.
        imm = inn[16:32]
        # NOTE: `ans` shadows the global variable `ans`.
        ans = BitArray(bin=imm).int
        decideCtrl("addi", file)
        addi(rt, rs, ans)


# Dedice on control signals
def decideCtrl(op, file):
    RegDst = "1"
    ALUSrc = "0"
    MemtoReg = "0"
    RegWrite = "1"
    MemRead = "0"
    MemWrite = "0"
    branch = "0"
    ALUOp1 = "1"
    ALUOp2 = "0"

    match op:
        case "add":
            # NOTE: `comm` seems to be unused.
            # NOTE: `comm` shadows the global variable `comm`.
            comm = "add"

        case "sub":
            # NOTE: `comm` seems to be unused.
            # NOTE: `comm` shadows the global variable `comm`.
            comm = "sub"

        case "addi":
            RegDst = "0"
            ALUSrc = "1"
            ALUOp1 = "0"
            # NOTE: `comm` seems to be unused.
            # NOTE: `comm` shadows the global variable `comm`.
            comm = "addi"

    file.write(RegDst + ALUSrc + MemtoReg + RegWrite + MemRead + MemWrite
               + branch + ALUOp1 + ALUOp2 + "\n")


# == Functions =================================================================
# NOTE: renamed the function parameters to avoid shadowing the global variables.x
def add(_rs, _rt, _rd):
    regValues[regMap[_rd]] = regValues[regMap[_rs]] + regValues[regMap[_rt]]


# NOTE: renamed the function parameters to avoid shadowing the global variables.x
def sub(_rd, _rs, _rt):
    regValues[regMap[_rd]] = regValues[regMap[_rs]] - regValues[regMap[_rt]]


# NOTE: renamed the function parameters to avoid shadowing the global variables.x
def addi(_rt, _rs, _imm):
    regValues[regMap[_rs]] = regValues[regMap[_rt]] + _imm


def main():

    PCount = 65536
    # NOTE: commented this line, because it's not being used anywhere.
    # QUESTION: where do you define the variable "filename"?
    # with open(filename, mode="r", encoding="utf-8") as file:
    #     storedLines = file.read().splitlines()

    ans = (
        str(regValues)
        .replace(",", "")
        .replace("[", "")
        .replace("]", "")
        .replace(" ", "|")
    )
    # NOTE: specified the `encoding` parameter, as it's a good practice.
    # NOTE: modified to `with open` as it's a good practice.
    with open("outputTwo.txt", mode = "w", encoding = "utf-8") as newFileTwo,\
        open("outputOne.txt", mode = "w", encoding = "utf-8") as newFile:
        newFileTwo.write(f"{PCount}|{ans}\n")

        # NOTE: creating some sample data for `F`, as I couldn't find it anywhere.
        F = [
            "0010000000000000000000000000000000",
            "0010000000000000000000000000000000",
            "0010000000000000000000000000000000",
            "0010000000000000000000000000000000",
            "0010000000000000000000000000000000",
            "0010000000000000000000000000000000",
            "0010000000000000000000000000000000",
            "0010000000000000000000000000000000",
            "0010000000000000000000000000000000",
            "0010000000000000000000000000000000",
        ]

        for count, comms in enumerate(F):
            if count == 100:
                # newFile.close()     # If you use `with open`, you dont't need to close the file.
                # newFileTwo.close()  # If you use `with open`, you dont't need to close the file.
                exit()
            PCount += 4
            program(comms, newFile, newFileTwo, PCount)


# Use open file to store the lines with their indicies
# When beq or bne compare and if:
# true -> grab label imm -> convert to decimal -> divide by 4 to get actual line

# Ad
# While `i` is less than the size of the lines array, iterate through it,
# and do the following logic:
#   storedLines[i] - line of a code in a file. Do logic to each [i]
# Add internal pc counter (`intpc=0`). By each iteration of `i`, `intpc` goes +4
# at the end  of while loop internalPC = 4
# i == internalPC // 4

# App Entry Point
if __name__ == "__main__":
    main()