Vi. python functions

Source: Internet
Author: User

Python functions

First, the function


A function is a group of statements that accomplishes a particular function, which can be used as a unit and give it a name

The function name can be executed multiple times in different places of the program (this is often called a function call), but it is not necessary to repeat these statements everywhere

Custom functions and pre-defined functions


Function: Reduce the difficulty of programming, code reuse


When we define a function ourselves, we usually use the DEF statement

def function name (parameter list): #可以没有参数

function body

#!/usr/bin/python

a = Int (raw_input ("Please enter a number:"))

b = Int (raw_input ("Please enter other number:"))

def fun ():

c = A + b

Print C

Fun ()


Formal parameters, actual parameters, default parameters

---the variable name in parentheses after the function name when defining the function is called the "formal parameter"

---the name of the variable in parentheses behind the function name when calling the function is called "actual parameter"

#!/usr/bin/python

#!coding:utf8

def fun (A, b): #形参

c = A + b

Print ("%d+%d=%d")% (a,b,c)

a = Int (raw_input ("Please enter a integer:"))

b = Int (raw_input ("Please enter B integer:"))

Fun (A, b) #实参


#!/usr/bin/python

#!coding:utf8

def fun (a,b=2): #默认 (simultaneous parameter assignment or the right-hand argument)

c = A + b

Print ("%d+%d=%d")% (a,b,c)

a = Int (raw_input ("Please enter a integer:"))

Fun (a)


Ii. Scope of variables

Local variables, global variables

#!/usr/bin/python

x = Ten #全局变量

def fun ():

x = 2 #局部变量

Print X

Fun ()

Print X


To change a local variable to a global variant (global)

#!/usr/bin/python

x = 10

def fun ():

x = 2

Global y

y = 111

Print X

Fun ()

Print X

Print Y


Third, function return value (returns)

>>> def f (x, Y):

... if x>y:

... return-1

... if x<y:

... return 1

... return 0

...

>>> F (+)

1

>>> F (a)

0

>>> F (2,1)

-1


Redundant parameter processing (* Receive tuple parameters, * * Receive dictionary parameters)

def f (X,*args,**kwargs):

Print X

Print args

Print Kwargs

>>> F (1,2,3,4,5,6,y=20,z=30)

1

(2, 3, 4, 5, 6)

{' Y ': +, ' Z ': 30}



Iv. Anonymous functions: Lambda

---Lambda function is the smallest function that quickly defines a single line

>>> def f (x, Y):

... return X*y

...

>>> F (2,3)

6


>>> g = Lambda x,y:x*y (the colon is preceded by a parameter and the colon is the return value)

>>> g (2,3)

6



Five, branch structure

The switch statement is used to write a multi-branch structure program, similar to the If...elif...else statement

The spoke structure expressed by the switch statement is clearer than the If...elif...else statement, and the code is more readable

But Python does not provide a switch statement

Pyhon can implement the switch statement function through a dictionary

#!/usr/bin/python

#coding: Utf-8

From __future__ Import Division

def a (x, y):

Return X+y

def b (x, y):

return x-y

def c (x, y):

Return X*y

def d (x, y):

return x/Y


def operator (X,o,y):

If o = = "+":

Print a (x, y)

If o = = "-":

Print b (x, y)

If o = = "*":

Print c (x, y)

If o = = "/":

Print d (x, y)

Print operator (3, "+", 1)


Can be written with branch structure (omit if judgment)

#!/usr/bin/python

#coding: Utf-8

From __future__ Import Division

def a (x, y):

Return X+y

def b (x, y):

return x-y

def c (x, y):

Return X*y

def d (x, y):

return x/Y

SW = {"+": A, "-": B, "*": C, "/":d}

def f (x,o,y):

Print Sw[o] (x, y)

F (3, "+", 2)



Vi. commonly used built-in functions (examples of several)

Len () #计算元素个数

>>> s = "Hello"

>>> Len (s)

5

Divmod () #计算两个数的模, output quotient, die

>>> Divmod (5,2)

(2, 1)

Pow () #计算一个数的幂或模

>>> Pow (2,3)

8

>>> Pow (2,3,2) #2的3次方除2的模

0

Round () #返回浮点数

>>> Round (2)

2.0

Min () #取最小值

Max () #取最大值

>>> min (+)

1

>>> Max (1,2,100,99)

100

Callable () #检测函数是否可以调用 true to invoke the

>>> callable (min)

True

Type () #判断类型

>>> Type (1)

<type ' int ' >

CMP () #比较两个字符串, same return 0, not same return-1

>>> CMP (+)

-1

>>> CMP (+)

0

Range () #生产一个序列

>>> Range (10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Xrange ()


Type conversions

int () # integral type

float () # float type

STR () # character type

List () #

Tuple () # tuple

Hex () # Returns a hexadecimal representation of an integer or a long integer.

Oct () # Returns an octal representation of an integer or a long integer.

Chr () # Returns a character order of a string I; 0 <= I < 256

Ord () # returns an integer sequence string of one character



Vii. built-in functions related to types


String handling functions

Str.capitalize () #控制字符串开头大写

>>> s = "Hello World"

>>> s.capitalize ()

' Hello World '

Str.replace () #替换字符

>>> s.replace ("Hello", ' good ')

' Good world '

Str.split () #切割字符

>>> IP = "192.168.21.1"

>>> ip.split ('. ')

[' 192 ', ' 168 ', ' 21 ', ' 1 ']

>>> ip.split ('. ') [1]

' 168 '

>>> ip.split ('. ', 1) #1表示切割次数

[' 192 ', ' 168.21.1 ']


Sequence processing functions

Len ()

Max ()

Min ()

Filter () #过滤

>>> L = Range (10)

>>> def f (x):

... if x>5:

.... return True

...

>>> Filter (F,L)

[6, 7, 8, 9]

Zip () #递进遍历

>>> t = [' Loyu ', ' love ', ' like ']

>>> t2 = [' 20 ', ' 30 ', ' 40 ']

>>> Zip (t,t2)

[(' Loyu ', ' ' A '), (' Love ', ' a '), (' Like ', ' 40 ')]

Map () #递进遍历

>>> t = [' Loyu ', ' love ', ' like ']

>>> t2 = [' 20 ', ' 30 ', ' 40 ']

>>> Zip (t,t2)

[(' Loyu ', ' ' A '), (' Love ', ' a '), (' Like ', ' 40 ')]

>>> t3 = [' 1 ', ' 2 ']

>>> Zip (T,T2,T3)

[(' Loyu ', ' A ', ' 1 '), (' Love ', ' 30 ', ' 2 ')]

>>> map (NONE,T,T2,T3) #None可以是函数

[(' Loyu ', ' 1 '), (' Love ', ' + ', ' 2 '), (' Like ', ' Max ', None)]

Reduce () #阶乘

>>> L = Range (1,101)

>>> reduce (lambda x,y:x+y,l)

5050


This article from "Meteor Yu" blog, declined reproduced!

Vi. python functions

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.