Python inline functions

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.