Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 嵌套函数的作用域问题_Python_Function_Scope_Nested - Fatal编程技术网

Python 嵌套函数的作用域问题

Python 嵌套函数的作用域问题,python,function,scope,nested,Python,Function,Scope,Nested,我在储蓄(储蓄)的def calculte\u利息中遇到意外的缩进错误。?可变储蓄在上面的同一行定义 def print_balance(): balance = 1000 print("Your balance is " + str(balance)) def deduct(amount): print("Your new balance is " + str(balance - amount)) savin

我在储蓄(储蓄)的def calculte\u利息中遇到意外的缩进错误。?可变储蓄在上面的同一行定义

def print_balance():
   balance = 1000
   print("Your balance is " + str(balance))

   def deduct(amount):
      print("Your new balance is " + str(balance -  amount))
      savings = balance-amount
 
   deduct(500)

      def calculte_interest_on_savings(savings):
        print("You will gain interest on: " + str     (savings))
    
      calculte_interest_on_savings(savings)     


print_balance()

我会这样写

def打印余额(余额):
打印(“您的余额为”+str(余额))
def扣除(金额、余额):
打印(“您的新余额为”+str(余额-金额))
储蓄=余额
返还储蓄
存款的def计算利息(存款):
打印(“您将在:+str(储蓄)上获得利息”)
余额=1000
打印余额(余额)
储蓄=扣除(500,余额)
储蓄(储蓄)的计算利息
打印余额(余额)

没有理由嵌套这些函数

def print_balance():
   balance = 1000
   print("Your balance is " + str(balance))
   savings = deduct(balance, 500)
   calculate_interest_on_savings(savings)  
  

def deduct(balance, amount):
    print("Your new balance is " + str(balance - amount))
    savings = balance - amount
    return savings
 

def calculate_interest_on_savings(savings):
    print("You will gain interest on: " + str(savings))


if __name__ == '__main__':
    print_balance()

问题是,假设问题中的代码缩进与您正在运行的实际代码相同,
def calculte…
缩进到上面一行的下方,该行的内容为
decreate(500)
-它应该与该行的缩进级别相同。这是否回答了您的问题?意外缩进是语法错误,而不是范围错误。尽管如此,在这段代码中范围界定似乎也是一个问题。顺便说一句,欢迎使用堆栈溢出!请拿着这本书读一读。