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

2024-04-28 23:51:48 发布

您现在位置:Python中文网/ 问答频道 /正文

那个么为什么结果并没有改变呢?结果是全局的,但即使在def add()打印正确答案时打印(结果),结果也将返回零

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))

Tags: addnumberinputyourdefresultoperationnum
2条回答

操作函数中的result变量与cal函数的作用域不同。让这些函数返回一个值,然后从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

相关问题 更多 >