Python Learning Note 2 function

Source: Internet
Author: User

1. Calling functions

ABS () method, calling the absolute value function

ABS (1) ABS ( -1) ABS (1.1)

CMP () method, Comparison function

CMP (() CMP (2,1) CMP

Data type conversions

Int (' 123 ') int (1,23) str (1)


2. Defining functions

Define an absolute value function

def my_abs (x): if x >= 0:return x else:return-x

Return returns the function value and represents the end of the call

Null function

Def Kong (): Pass

Pass represents empty, if not fill in will error

Parameter check

def my_abs (x): If not isinstance (x, (Int,float)): Raise TypeError (' bad operand tpye ') if x >= 0:ret Urn x else:return-x

Isinstance (value, type) to check if the value is the corresponding type

Raise represents throwing an error and ending without executing the code behind

Return multiple values

def sum (a,b,c): x = a + b y = b + c z = a + c return z/y


3. Parameters of the function

Default parameters

def power (x): return x * x
def power (x,n=2): s = 1 while n > 0:n = n-1 s = S * x return s

Variable parameters

Def calc (*numbers): sum = 0 for n in numbers:sum = sum + N * N return sumnums = [1,2,3]calc (*nums)

Variable parameters allow automatic assembly of arbitrary parameters into tuples

Keyword parameters

def person (name,age,**kw): print ' name: ', Name, ' Age: ', age, ' other: ' kwkw = {' City ': ' Beijing ', ' job ': ' Engineer '}person (' Jack ', 27,**kw)

The keyword parameter allows automatic assembly of any parameter into a dictionary

Parameter combinations

def func (a,b,c=0,*args,**kw): print ' a= ', A, ' b= ', B, ' c= ', C, ' args= ', args, ' kw= ', Kwargs = (1,2,3,4) kw = {' X ':} func (*ar GS,**KW) A = 1 b = 2 c = 3 args = (4) kw = {' X ': 99}


4. Recursive functions

Recursive functions

def fact (n): if n = = 1:return 1 return n * Fact (N-1) fact (1) fact (5)


This article is from the "Eight Miles" blog, so be sure to keep this source http://5921271.blog.51cto.com/5911271/1726069

Python Learning Note 2 function

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.