"Python Tour" chapter III (i): Python functions

Source: Internet
Author: User

Description

using functions to make the program function modular, greatly concise our program, here is the main discussion of Python functions in the following content:

1. Function definitions and function parameters 2. Local variables and global Variables 3. Function default parameters and key parameters 4.*args and **kargs

Because part of the function is very similar to much of the C language, it will be combined with the C language for comparative study.



1. function definition and Function parameters


--Basic Format 1: Non parameter

Custom

Def sayhi (): print "hello!"

Call

>>> Sayhi () Hello


--Basic Format 2: with one parameter

Custom

def sayhi (name): print "Hello,%s, how is it?"% Name

Call

>>> sayhi (' xpleaf ') Hello, xpleaf, how is it?


--Basic Format 3: Multiple parameters

Custom

def sayhi (name, age): Print "Hello,%s, how is it?"% Name print "You is%s years old."

Call

>>> sayhi (' cl ', +) Hello, CL, how is it? Years old.



2. Local variables and global variables


• Look at one of the following programs:

#!/usr/bin/env pythonage = 29def sayhi (): Age = + print "function age:%s"% agesayhi () print "gloable Age:", Age

• Execution results are as follows:

[Email protected]:/mnt/hgfs/python/day3$ Python fun3.py function age:28gloable age:29


· In Python functions, the concept of scope is the same as in C, no longer mentioned here;

• There are two points to note:

A. By changing global variables by local variables, you can use global in the function, as follows:

Def sayhi (): Global age = print "function age:%s"% age

B. Global variables are not defined, and global definitions are used in the function, which is equivalent to defining globals, but not recommended;



4. Function default parameters and key parameters


--Function default parameters

• Look at one of the following programs:

#!/usr/bin/env Pythondef Users (username, group = ' Gdut '): Mydict = {} Mydict[username] = group return Mydictprint "Default argument:", Users (' xpleaf ') #use default Argumentprint "full argument:", Users (' Xpleaf ', ' BAT ') #do Not use default argument

• Execution results are as follows:

[Email protected]:/mnt/hgfs/python/day3$ Python default.py default argument: {' xpleaf ': ' Gdut '}full argument: {' Xpleaf ' : ' BAT '}

• When defining a function, the parameter is assigned by default, which is the default parameter when the function is used without assigning a value to such a parameter;


• The principle of using default parameters: When defining a function, the default parameter is in front of the first, and the defaults are after;

• If the following is illegal:

#!/usr/bin/env pythondef Users (group = ' Gdut ', name): Mydict = {} Mydict[username] = group return myd Ictprint "Default argument:", Users (' xpleaf ') #use default argument# compiler will not know whether ' xpleaf ' is assigned to the group variable or the name variable print "full Argument: ", Users (' Xpleaf ', ' BAT ') #do not use default argument

• Prompt error during execution: non-default argument follows default argument

[Email protected]af-machine:/mnt/hgfs/python/day3$ Python default.py File "default.py", Line 3 def users (group = ' GDU T ', name): syntaxerror:non-default argument follows default argument


--Function Key parameters

• In a function that uses multiple default parameters, the following program:

#!/usr/bin/env pythondef Users (name, age, group = ' Gdut ', project = ' Python '): print ' Name:%sage:%sgroup:%sprojec t:%s "% (name, age, group, Project) users (' Xpleaf ', 21)

• Execution results are as follows:

[Email protected]:/mnt/hgfs/python/day3$ Python default.py Name:xpleafage:21group:gdutproject:python


-Specify only the first default parameter


• The corresponding users ' code is modified to:

Users (' xpleaf ', +, ' BAT ')

• Execution results are as follows:

[Email protected]:/mnt/hgfs/python/day3$ Python Default.pyname:xpleafage:21group:batproject:python


-Specify two default parameters at a time


• The corresponding users ' code is modified to:

Users (' xpleaf ', +, ' BAT ', ' stupy ')

• Execution results are as follows:

[Email protected]:/mnt/hgfs/python/day3$ Python default.pyname:xpleafage:21group:batproject:stupy


-just specify a second default parameter


• The corresponding users ' code is modified to:

Users (' xpleaf ', +, project = ' stupy ')

• Execution results are as follows:

[Email protected]:/mnt/hgfs/python/day3$ Python default.pyname:xpleafage:21group:gdutproject:stupy

• Specify the second parameter, which is the key parameter, and can not be in the order of the original parameters (without specifying the key parameters will not achieve the purpose);

• You can also specify more than one default parameter so that the users code is modified as follows instead of the location of the original parameter:

Users (project = ' Stupy ', name = ' Xpleaf ', age = +, group = ' BAT ')

• Execution results are as follows:

[Email protected]:/mnt/hgfs/python/day3$ Python default.pyname:xpleafage:21group:batproject:stupy


-Clearer examples


• The program code is as follows:

#!/usr/bin/env pythondef func (A, b=5, c=10): print ' a=%s, b=%s, c=%s '% (a, B, c) func (3, 7) func (25,c=24) func (c=50, A=100)

• Execution results are as follows:

Func (3, 7) # a = 3, b=7,c=10 func (c=24) # a=25, b=5,c=24 func (c=50, a=100) # a=100,b=5,c=50



4.*args and **kargs


• Using *args and **kargs in the case of uncertain parameters, the former can output parameters corresponding to the tuple, the latter can output the dictionary corresponding to the parameters;


The *args demo is as follows:

A. Program code

def sayhi (*args): Print argssayhi (' xpleaf ', +, ' Gdut ')

B. Results of implementation

[Email protected]:/mnt/hgfs/python/day3$ Python fun2.py (' xpleaf ', +, ' Gdut ')


The **kargs demo is as follows:

A. Program code

def sayHi2 (**kargs): Print kargssayHi2 (name = ' Xpleaf ', age=21, phone = 5201314)

B. Results of implementation

[Email protected]:/mnt/hgfs/python/day3$ Python fun2.py {' phone ': 34234, ' age ': ' Name ': ' Alex '}

• Because dictionaries are not sequential, the order of output is different from the input.


This article is from the "fragrant fluttering leaves" blog, please make sure to keep this source http://xpleaf.blog.51cto.com/9315560/1696907

"Python Tour" chapter III (i): Python 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.