Nesting Functions and Decorators (1/2) (Theory of Python) (Python Tutorial)

preview_player
Показать описание
Understanding how functions nest in Python is key to uncovering decorators. Here we examine the syntax and behavior of nested functions as well as the nonlocal statement.

Thank you!
Рекомендации по теме
Комментарии
Автор

def make_sum():
a = 1
def add(x):
nonlocal a
if x == 0 or x == 1:
return 1
else:
a = a + x
return a
return add


b = make_sum()
b(0)








video helped me out on the summator problem ..






THe previous output plus the current output is the new output.


current output = input + previous output.


I used some conditional statements for x = 0 and x = 1 .


So far it works.

phazon
Автор

You really doing a good job carry-on👍.

عبدالعزيزالحربي-رل
Автор

Hi there. Long time sub here. So, I've been practicing lately, and in this simple code I created, I'm just trying to understand why I get a value of 9. I desire a result of 12. I'm just learning how to rewrite this in different ways.






def double(a):
b = 2 * a
def triple(b):

return 3 * b
return triple



d = double(2)
c = d ( 3)

phazon
Автор

Why do I need to include “nonlocal a”? Why doesn’t the inc function naturally expand its search for the a variable to the global level after it fails to locate it at the local level?

charlieraith
Автор

I really dont understand why when after following all your steps i write inc() and i get a higher value each time, BUT not if i run incrementor()() even thou inc=incrementor(). Also why cant i check the value of a by simply typing a in cmd?

grzegorzgrzelczyk
Автор

so all the function reserve their name in global space and local space? I mean calling a nested function in the global space and assigning something else to that name, would this give us an error?

TheGiantGi
Автор

This incrementer example is just a closure, right? The scope of inc() encloses the part of the scope of incrementer specified using nonlocal.

glan-tucan
visit shbcf.ru