python 中的全局变量不会改变子函数

global variable in python that doesn't make change in sub function

那么为什么结果没有改变?结果是全局的,但即使 def add() 中的 print(result) 打印正确答案,它也会 return 为零。

number = int(input("enter your first num: "))
operation = input("enter your operation: ")
second_number = int(input("enter your second num: "))

def cal(num1,op,num2):
    result = 0
    def add():
        result = num1+num2
        print(result)
    def multiply():
        result =  num1 * num2
    def devide():
        if not num2==0:
            result = num1 / num2
        else:
            result = 'num2 can\'t be zero'
    def default():
        print("Incorrect option")
    switch = {
        '+':add,
        '*':multiply,
        '/':devide
    }
    switch.get(op,default)()
    return result

            
    
print(cal(number,operation,second_number))

运算函数中的result变量与cal函数的作用域不同。让这些函数 return 一个值,然后 return 来自 cal 的值,您将获得所需的行为。

def cal(num1,op,num2):
    def add():
        return num1+num2
    def multiply():
        return num1 * num2
    def devide():
        if not num2==0:
            result = num1 / num2
        else:
            result = 'num2 can\'t be zero'
        return result
    def default():
        print("Incorrect option")
    switch = {
        '+':add,
        '*':multiply,
        '/':devide
    }
    return switch.get(op,default)()

全局结果超出范围。

number = int(input("enter your first num: "))
operation = input("enter your operation: ")
second_number = int(input("enter your second num: "))


def cal(num1, op, num2):

    def add():
        result = num1+num2
        return result

    def multiply():
        result = num1 * num2
        return result

    def devide():
        if not num2 == 0:
            result = num1 / num2
            return result
        else:
            result = 'num2 can\'t be zero'
            return result

    def default():
        print("Incorrect option")
        switch = {
        '+': add,
        '*': multiply,
        '/': divide
        }
    return switch.get(op, default)()


print(cal(number, operation, second_number))


Python program that uses global
def method():
    # Change "value" to mean the global variable.
    # ... The assignment will be local without "global."
    global value
    value = 100

value = 0
method()

# The value has been changed to 100.
print(value)
100`


Python program that uses nonlocal
def method():

    def method2():
        # In nested method, reference nonlocal variable.
        nonlocal value
        value = 100

    # Set local.
    value = 10
    method2()

    # Local variable reflects nonlocal change.
    print(value)

# Call method.
method()
100