Local Variables
def discount (price, rate):
Final_price = Price * Rate
Return Final_price
Old_price = float (Input (' Enter Price: ')) global variable
Rate = Float (input (' Please enter discount ratio: '))
New_price = Discount (old_price, rate)
Print (' Price after Discount: ', New_price)
Print (the value of ' Print local variable final_price: ',final_price) is shown as a defined variable, Final_price is a variable in the discount function, is a local variable, and the discount is invalid.
Defining global variables in local variables
>>> test1 = 5
>>> def Change ():
Test1 = 10
Print (test1)
>>> Change ()
10
>>> test1
5
>>> def Change ():
Global Test1
Test1 = 10
Print (test1)
>>> Change ()
10
>>> test1
10
inline functions
>>> def fun1 ():
Print (' fun1 is being called: ')
Def fun2 ():
Print (' fun2 is being called ... ')
Fun2 ()
>>> fun1 () call FUN1 () to execute call FUN2 ()
FUN1 is being called:
Fun2 is being called ...
closures If in an intrinsic function, a reference to a variable in the outer scope
>>> def fun3 (x):
def fun4 (y):
return x * y
Return FUN4
>>> Fun3 (1)
<function Fun3.<locals>.fun4 at 0x0000000002f549d8>
>>> type (FUN3)
<class ' function ' >
>>> fun3 (1) (2)
2
>>> def fun1 ():
x = 5
Def fun2 ():
X *= x
return x
Return fun2 ()
>>> fun1 ()
Traceback (most recent):
File "<pyshell#52>", line 1, in <module>
FUN1 ()
File "<pyshell#50>", line 6, in FUN1
Return fun2 ()
File "<pyshell#50>", line 4, in fun2
X *= x
unboundlocalerror:local variable ' x ' referenced before assignment
>>> def fun1 ():
x = 5
Def fun2 ():
nonlocal x Force Declaration of non-local variables
X *= x
return x
Return fun2 ()
>>> fun1 ()
25
Python inline functions