简体   繁体   English

我的代码中的 Python“回溯错误”,不确定如何解决

[英]Python "traceback error" in my code, unsure how to solve

Good evening StackOverflow users! StackOverflow 用户晚上好! I'm working on a python code that does the following:我正在处理执行以下操作的 python 代码:

the user will enter values of two, 3x3 matrices and then select from options including, addition, subtraction, matrix multiplication, and element by element multiplication.用户将输入两个 3x3 矩阵的值,然后从包括加法、减法、矩阵乘法和逐元素乘法在内的选项中进行选择。 You should use numpy.matmul() for matrix multiplication (eg np.matmul(a, b) ).您应该使用numpy.matmul()进行矩阵乘法(例如np.matmul(a, b) )。 The program should compute the appropriate results and return the results, the transpose of the results, the mean of the rows for the results, and the mean of the columns for the results程序应该计算适当的结果并返回结果、结果的转置、结果的行的平均值以及结果的列的平均值

However, the code as I have it, produces an error message as follows.但是,我拥有的代码会产生如下错误消息。

Traceback (most recent call last):
  File "C:/Users/jwhoc/OneDrive/Documents/Python Tests/week4_lab.py", line 40, in <module>
    print(a[i][j],end=" ")
IndexError: list index out of range

This error message occurs after you enter your 3x3 matrix the first time.第一次输入 3x3 矩阵后会出现此错误消息。 I'll insert the code below.我将在下面插入代码。

import numpy as np
import re
print("*******************************Welcome to the Python Matrix Application*******************")
while True:
    print("Do you want to play the Matrix Game?")
    #Reading the choice
    choice=input("Enter Y for yes or N for No:")
    if choice=="N":
        print("****************Thanks for playing Python Numpy************************")
        break
    else:
        while True:
            phone=input("Enter your phone number(XXX-XXX-XXXX):")
            #Regular expression for checking the phone number format
            if not re.match("\d{3}-\d{3}-\d{4}",phone):
                print("Your phone number is not in correct format. Please reenter:")
            else:
                break
        while True:
            zip=input("Enter your zipcode+4(XXXXX-XXXX):")
            #Regular expression for checking the zipcode format
            if not re.match("\d{5}-\d{4}",zip):
                print("Your zipcode is not in correct format. Please reenter:")
            else:
                break
        #Reading the first matrix
        print("Enter your first 3x3 matrix:")
        a=[]
        for i in range(3):
            #Reading row by row
            row=input().split()
            #Converting each element to integer
            row=list(map(int,row))
            #Adding row to the matrix
            a.append(row)
        #Printing first matrix
        print("Your first 3x3 matrix is:")
        for i in range(3):
            for j in range(3):
                print(a[i][j],end=" ")
            print()

Any help you all can give would be fantastic.你们能提供的任何帮助都会很棒。 Thanks guys!谢谢你们!

I run your code and it works perfectly, but I think the problem that you may had was the form that you introduce your inputs.我运行您的代码并且它运行良好,但我认为您可能遇到的问题是您引入输入的形式。 For example: If you provide the rows in this way there's no problem:例如:如果您以这种方式提供行,则没有问题:

2 5 6

But if you did it like this:但如果你这样做:

256

You will get the same error that you say, that's because when your calling你会得到和你说的一样的错误,那是因为当你打电话时

row = input().split()

you are not getting [2, 5, 6] , but [256] instead.你得到的不是[2, 5, 6] ,而是[256] That's because the default separator of split() function is a space.那是因为 split() 函数的默认分隔符是一个空格。 In case you want to introduce the values in this way 256 , you should change row = input().split() to如果您想以这种方式引入值256 ,您应该将row = input().split()更改为

row = input().split("")

Note that there's not space in ""请注意,“”中没有空格

The issue is that matrics input does conform the required format.问题是矩阵输入确实符合所需的格式。 str.split() splits on the " " character unless otherwise specified so numbers must be separated by spaces. str.split()在 " " 字符上拆分,除非另有说明,因此数字必须用空格分隔。 I think it might be helpful to do some error checking on the matrix inputs similarly to earlier inputs.我认为与早期输入类似,对矩阵输入进行一些错误检查可能会有所帮助。 Try this out:试试这个:

import re
print("*******************************Welcome to the Python Matrix Application*******************")
while True:
    print("Do you want to play the Matrix Game?")
    #Reading the choice
    choice=input("Enter Y for yes or N for No:")
    if choice=="N":
        print("****************Thanks for playing Python Numpy************************")
        break
    else:
        while True:
            phone=input("Enter your phone number(XXX-XXX-XXXX):")
            #Regular expression for checking the phone number format
            if not re.match("\d{3}-\d{3}-\d{4}",phone):
                print("Your phone number is not in correct format. Please reenter:")
            else:
                break
        while True:
            zip=input("Enter your zipcode+4(XXXXX-XXXX):")
            #Regular expression for checking the zipcode format
            if not re.match("\d{5}-\d{4}",zip):
                print("Your zipcode is not in correct format. Please reenter:")
            else:
                break
        #Reading the first matrix
        print("Enter your first 3x3 matrix:")
        a=[]
        for i in range(3):
            while True
                #Reading row by row
                row=input().split()
                #Converting each element to integer
                row=list(map(int,row))
                if len(row) != 3:
                    print(f"Needs 3 numbers. {len(row)} numbers specified. Please re-enter:")
                else:
                    break
            #Adding row to the matrix
            a.append(row)
        #Printing first matrix
        print("Your first 3x3 matrix is:")
        for i in range(3):
            for j in range(3):
                print(a[i][j],end=" ")
            print()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM