if语句中的变量问题

时间:2016-08-21 04:55:37

标签: python variables if-statement

我刚开始使用python,我决定从一个简单的程序开始,将一行,两个参数数学表达式直接解析成答案。示例:4 + 2,3 / 4,5435 * 3423等。首先,我尝试解释方程中的两个变量,然后才开始让程序对它们进行数学化。我的问题是第39,40,42和43行没有在1,3,2和5修改它们各自的变量。在PyCharm中,它们是灰色的,带有关于阴影名称超出范围的错误。

目前差不多凌晨1点,我的夜猫子并不多(我永远不会把它变成编码器大声笑)所以这可能是我犯下的一个愚蠢的错误,但仅仅是情况下...

primeNumber = None
secNumber = None
num11 = 0
buildList = []
finished = False

def interpret(statement):
    i = 0
    iMax = len(statement)
    while True:
        if i >= iMax:
            break
        parse(statement[i])
        i = i + 1

def parse(char, buildList=buildList):
    interrupt = [" ", "+", "-", "/", "*"]
    if char in interrupt:
        buildNumber(buildList)
        buildList.clear()
    elif num11 == 1:
        buildNumber(buildList)
        buildList.clear()
    else:
        buildList.append(char)

def isNumber(att):
    try:
        int(att)
        return True
    except ValueError:
        return False

def buildNumber(finishedList, num11 = num11):
    finishedNumber = ''.join(finishedList)
    print(finishedNumber)

    if num11 == 0:
        primeNumber = finishedNumber # <<< line 39
        num11 = 1
    elif num11 == 1:
        secNumber = finishedNumber
        finished = True

1 个答案:

答案 0 :(得分:0)

在Python中,如果在函数中设置了它们的值,则假定函数内部引用的变量是本地的。要覆盖此默认行为,并从函数内部设置全局变量,您需要使用global语句声明它们(仅当您要它们时,您不需要预先声明他们他们。)

你的代码的其他问题:你随机混合访问全局变量与遍历全局变量和默认为全局变量 - 你应该最小化你的全局变量并一致地对待它们;选择更多描述性变量名称(为什么期望SO上的人猜出num11的意思?);不要重新发明布尔(num11再次);你过早地开始构建第二个数字。

我已经考虑到上述问题重新编写了代码,并添加了足够的包装和粘合代码以使其运行:

firstNumber = None
secondNumber = None
finishedFirst = False
finishedSecond = False
operation = None

operations = {
    " ": None,
    "+": lambda a, b: a + b,
    "-": lambda a, b: a - b,
    "/": lambda a, b: a / b,
    "*": lambda a, b: a * b,
}

def interpret(statement):
    buildList = []

    for character in statement:
        parse(character, buildList)

    if not finishedSecond:
        buildNumber(buildList)

def parse(character, buildList):
    global operation

    if character in operations:
        if buildList:
            buildNumber(buildList)
            buildList.clear()
        if operations[character] is not None:
            operation = operations[character]
    else:
        buildList.append(character)

def buildNumber(finishedList):
    global firstNumber, secondNumber, finishedFirst, finishedSecond

    finishedNumber = ''.join(finishedList)

    if not finishedFirst:
        firstNumber = int(finishedNumber)
        finishedFirst = True
    else:
        secondNumber = int(finishedNumber)
        finishedSecond = True

statement = input("> ")

interpret(statement)

print(operation(firstNumber, secondNumber))

示例

python3 test.py
> 34 + 56
90