gpt4 book ai didi

python - 没有 NumPy 的矩阵计算器 - 将参数传递给其他函数

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:26 25 4
gpt4 key购买 nike

所以我正在构建一个没有 NumPy 的矩阵计算器,并且我有一个有限但有效的模型。然而该模型非常粗糙,我想对其进行改进并扩展其功能,以便能够计算多个矩阵并相互交互(例如乘法)。

由于我对 Python 的经验非常有限,我很快遇到的一个问题是在多个函数之间传递变量(我相信它们被称为参数)。这是我所拥有的:

def matrixGenerator1():
rows = int(input("\nHow many rows are in the matrix?\n\n:"))
columns = int(input("\nHow many columns are in the matrix?\n\n:"))
matrix1 = [[0 for x in range(columns)] for y in range(rows)]
for y in range(rows):
for x in range(columns):
matrix1[y][x] = int(input("\nWhat is the entry?\n\n:"))
print("\nThe original matrix is...")
for y in range(rows):
print("\n")
for x in range(columns):
print(format(matrix1[y][x], "5d"), end="")
return rows, columns, matrix1


def matrixTranspose(rows, columns, matrix1):
print("\nThe transpose of this matrix is...")
for y in range(rows):
print("\n")
for x in range(columns):
print(format(matrix1[y][x], "5d"), end="")

matrixGenerator1()
matrixTranspose(rows, columns, matrix1)

运行此命令会产生一条错误消息,指出 rowscolumnsmatrix1 未定义。我意识到这些变量是matrixGenerator函数的本地变量,并且强制它们成为全局变量并不是我想要接受的选项。

是否有人可以向我提供关于我做错了什么的一般解释,以便我可以防止将来出现此错误?

最佳答案

您需要将第一个函数的输出保存在主例程中。 (请注意,您已经将其归还,因此您即将完成):

rows, columns, matrix1 = matrixGenerator1()
matrixTranspose(rows, columns, matrix1)

关于python - 没有 NumPy 的矩阵计算器 - 将参数传递给其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40365456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com