首页 > 解决方案 > 程序功能不起作用。它不能传递变量

问题描述

好吧,我想制作一个检查盒子数量的程序。但我的 python 程序不起作用。我用过python导师,所以,我知道这个原因。函数(=def)不能传递变量。我不知道为什么会出现这个问题......

a = 1

nsave = 100
vsave = 100
msave = 100
csave = 100

nsell = 0
vsell = 0
msell = 0
csell = 0

matrix = [[0]*3 for i in range(4)]
matrix[0][0] = "Nomal"
matrix[0][1] = nsave
matrix[0][2] = nsell
matrix[1][0] = "Vegetable"
matrix[1][1] = vsave
matrix[1][2] = vsell
matrix[2][0] = "Meat"
matrix[2][1] = msave
matrix[2][2] = msell
matrix[3][0] = "Cheese"
matrix[3][1] = csave
matrix[3][2] = csell


def choice(a):
    if (a == 1):
        nsave = nsave-1
        nsell = nsell+1
        if (matrix[0][1] < 0):
            print("error")
        else:
            for i in range(len(matrix)):
                for j in range(len(matrix[i])):
                    print(matrix[i][j])
                    print()

    else:
        print("Error")

标签: python

解决方案


这是您更正的代码:

a = 1

nsave = 100
vsave = 100
msave = 100
csave = 100

nsell = 0
vsell = 0
msell = 0
csell = 0

matrix = [[0]*3 for i in range(4)]
matrix[0][0] = "Nomal"
matrix[0][1] = nsave
matrix[0][2] = nsell
matrix[1][0] = "Vegetable"
matrix[1][1] = vsave
matrix[1][2] = vsell
matrix[2][0] = "Meat"
matrix[2][1] = msave
matrix[2][2] = msell
matrix[3][0] = "Cheese"
matrix[3][1] = csave
matrix[3][2] = csell


def choice(a):
    global nsave
    global nsell

    if (a == 1):
        nsave = nsave-1
        nsell = nsell+1
        if (matrix[0][1] < 0):
            print("error")
        else:
            for i in range(len(matrix)):
                for j in range(len(matrix[i])):
                    print(matrix[i][j])
                    print()

    else:
        print("Error")

choice(a)

推荐阅读