Python BASICS (7) -- Functions

Source: Internet
Author: User

This article describes how to organize statements into functions, the concept of parameters, and their usage in programs.

URL: http://www.cnblogs.com/archimedes/p/python-abstract.html.

Create a function

The built-in callable function can be used to determine whether the function is callable:

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

Use del statements to define functions:

>>> def hello(name):      return 'Hello, '+name+'!'>>> print hello('world')Hello, world!>>> print hello('Gumby')Hello, Gumby!

Compile a function of the fibnacci series:

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

Assigning values to parameters in a function does not change the values of any external variables:

>>> def try_to_change(n):      n='Mr.Gumby'>>> name='Mrs.Entity'>>> try_to_change(name)>>> name'Mrs.Entity'

Because strings (as well as tuples and numbers) cannot be changed, the parameters will not change. However, what will happen 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 parameter has changed, which is an important difference from the previous example.

Do not use the following function again:

>>> Name = ['Mrs. entity ', 'Mrs. thing ']> n = name # Again, simulate parameter passing behavior> n [0] = 'Mr. gumby' # change the list> name ['Mr. gumby', 'Mrs. thing ']

When two variables reference a list at the same time, they do reference a list at the same time. To avoid this situation, you can copy a copy of the list. When slicing is performed in the sequence, the returned slice is always a copy, so if you copy the slice of the entire list, you will get a copy:

>>> names=['Mrs.Entity','Mrs.Thing']>>> n=names[:]>>> n is namesFalse>>> n==namesTrue

Changing n does not affect 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

Parameters can be ordered by providing the parameter name (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 keyword parameter is that the default value can be provided to the 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!

It is not difficult to implement the function by providing any number of parameters:

>>> def print_params(*params):      print params>>> print_params('Testing')('Testing',)>>> print_params(1,2,3)(1, 2, 3)

Mixed common 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 indicates "collecting other location parameters". If no element is provided for collection, params is an empty tuples.

However, keyword 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 "**":

>>> 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 }>>> parames (1, 2) 1 2 3 () {}>>> def print_params_3 (** params ): print params >>> print_params_3 (x = 1, y = 2, z = 3) {'y': 2, 'x': 1, 'z ': 3 }>>> # The returned value is a dictionary instead of a tuples >>## composite '#' and '##' >>> def print_params_4 (x, y, z = 3, * pospar, ** keypar): print x, y, z print pospar 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 (){}

 

 

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.