Examples of functional usages of Python basics _python

Source: Internet
Author: User

This paper describes the use of Python functions in detail in the form of examples, which is of great value to beginners ' friends in Python. Share for everyone to use for reference. The specific analysis is as follows:

In general, the Python function is written by a new statement that DEF,DEF is an executable statement-the function does not exist until Python runs the def.

Functions are passed by assignment, and parameters are passed to the function by assignment

The DEF statement creates a function object and assigns it to a variable name, and the general format of the DEF statement is as follows:

def <name> (arg1,arg2,arg3,......,argn):

<statements>

A def statement is executed in real time, and when it runs, it creates and assigns a new function object to a variable name, and all of the statements in Python are executed in real time without a process like independent compile time

Because it is a statement, Def can appear where any statement can occur-or even nested within other statements:

if test:
  def fun ():.
else:
  def func ():
    .
...
Func ()

You can assign a function to a different variable name and invoke it with a new variable name:

Othername=func ()
othername ()

Create a function

The built-in callable function can be used to determine whether a function can be invoked:

>>> Import Math
>>> x=1
>>> y=math.sqrt
>>> callable (x)
False
>>> callable (y)
True

To define a function using the DEL statement:

>>> def Hello (name): Return
 ' Hello, ' +name+ '! '
>>> Print Hello (' world ')
Hello, world!
>>> Print hello (' Gumby ')
Hello, gumby!

Write a fibnacci sequence function:

>>> def fibs (num):
  result=[0,1] for
  i in range (num-2):
    result.append (result[-2]+result[-1) ) return result
>>> fibs
[0, 1, 1, 2, 3, 5, 8,,
MB
] >>> fibs [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

Assigning a value to a parameter within a function does not change the value of any external variable:

>>> def try_to_change (n):
 n= ' Mr.gumby '
>>> name= ' mrs.entity '
>>> try_to_ Change (name)
>>> name
' mrs.entity '

Because strings (and tuples and numbers) are immutable, they do not change when they are made, but what happens when a variable data structure such as a list is used as a parameter:

>>> name= ' mrs.entity '
>>> try_to_change (name)
>>> name
' mrs.entity '
>>> def Change (n):
  n[0]= ' Mr.gumby '

>>> name=[' mrs.entity ', ' mrs.thing ']
>> > Change (name)
>>> name
[' Mr.gumby ', ' mrs.thing ']

The parameters have changed, which is the important difference from the previous example

Do not use the following function again:

>>> name=[' mrs.entity ', ' mrs.thing ']
>>> n=name #再来一次, analogue reference behavior
>>> n[0]= ' Mr.gumby ' #改变列表
>>> name
[' Mr.gumby ', ' mrs.thing ']

When 2 variables refer to a list at the same time, they do refer to a list at the same time, to avoid this situation, you can copy a copy of a list, when slicing in the sequence, the returned slices are always a copy, so copy the entire list of slices, you will get a copy:

>>> names=[' mrs.entity ', ' mrs.thing ']
>>> n=names[:]
>>> n is names
False
>>> n==names
True

Changing n At this time does not affect the names:

>>> n[0]= ' Mr.gumby '
>>> n
[' Mr.gumby ', ' mrs.thing ']
>>> names
[' Mrs.entity ', ' mrs.thing ']
>>> change (names[:])
>>> names
[' mrs.entity ', ' Mrs.thing ']

Keyword parameters and default values

The order of the parameters can be provided by giving the parameter the name of the parameter (but the parameter name and value must correspond):

>>> def hello (greeting, name):
    print '%s,%s! '% ( Greeting, name)
>>> hello (greeting= ' hello ', name= ' world! ')
hello,world!!

The most powerful thing about keyword parameters is that you can provide a default value to a parameter in a parameter:

>>> def hello_1 (greeting= ' Hello ', name= ' world! '):
  print '%s,%s! '% ( Greeting,name)

>>> hello_1 ()
hello,world!!
>>> hello_1 (' Greetings ')
greetings,world!!
>>> hello_1 (' greeting ', ' universe ')
greeting,universe!

If you want greeting to use the default value:

>>> hello_1 (name= ' Gumby ')
hello,gumby!

You can provide any number of parameters to a function, and it is not difficult to implement:

>>> def print_params (*params):
  print params

>>> print_params (' testing ')
(' Testing ',)
>>> print_params (1,2,3)
(1, 2, 3)

Mixed General Parameters:

>>> def print_params_2 (title,*params):
  print title
  print params

>>> print_params_2 (' params: ', 1,2,3)
Params:
(1, 2, 3)
>>> print_params_2 (' Nothing: ') Nothing
:
()

The asterisk means "collect the rest of the positional parameters", and if you don't provide any elements for collection, params is a null tuple.

However, key parameters cannot be processed:

>>> print_params_2 (' Hmm ... ', something=42)
Traceback (most recent call last):
 File "<pyshell#112 > ", Line 1, in <module>
  print_params_2 (' Hmm ... ', something=42)
typeerror:print_params_2 () got an Unexpected keyword argument ' something '

Try to use "* *":

>>> def print_params (**params):
  print params

>>> print_params (x=1,y=2,z=3)
{' Y ': 2, '  X ': 1, ' Z ': 3}
>>> def parames (x,y,z=3,*pospar,**keypar):
  print x,y,z
  print Pospar
  print Keypar

>>> parames (1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{' foo ': 1, ' Bar ': 2}
>& Gt;> parames (1,2)
1 2 3
()
{}
>>> def print_params_3 (**params):
  print params< C18/>>>> Print_params_3 (x=1,y=2,z=3)
{' Y ': 2, ' X ': 1, ' Z ': 3}
>>> #返回的是字典而不是元组
> >> #组合 ' # ' and ' # # '
>>> def print_params_4 (x,y,z=3,*pospar,**keypar):
  print x,y,z
  print PO Spar
  Print Keypar

>>> print_params_4 (1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{' Foo ': 1, ' Bar ': 2}
>>> print_params_4 (1,2)
1 2 3
()
{}

It is believed that this article has certain reference value to everyone's study of Python programming.

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.