Python basics 3: functions, ternary functions, lambda functions, pythonlambda

Source: Internet
Author: User

Python basics 3: functions, ternary functions, lambda functions, pythonlambda

Functions: include user-defined functions and built-in functions

1) custom function structure:There are five parts:

  • Def Keyword:Identification used to create functions

  • Function Name:For example, f1

  • ():() Contains parameters.

  • Function body:Specific functions to be implemented by this function

  • Return:Return value. If none exists, none is returned.

As follows:

2) function call:Use the function name + ()

Format: function name (parameter 1, parameter 2), such as f1 (5, 8)

3) execution sequence of functions:From top to bottom.

The function body is executed only when it is called.

If you want to obtain the return value of the function, you need to assign a value.

The return Statement in the function body is no longer executed.

Execution result:

Case 1: do not execute a UDF because the UDF is not called.

def f1():
print('123')
return "111"


Case 2: Call a function and execute the function body. Once return is executed in the function body, it is terminated immediately, so the subsequent print (456) will never be executed.

def f1():
print('123')
return "111"
  print(456)
f1()

Case result: 123

Case 3: The result is 123 and 111, because a return value is given to r, print (r) and print 111.

Def f1 ():
Print ('20140901 ')
# In case of return, the function body is terminated immediately,
Return "111" # assign 111 to r
R = f1 ()
Print (r)

Case results: 123 and 111

Case 4: When the function does not return, the automatic default return value is None; the return result is 123 and None. Because no return is returned, the value accepted by r is None.

def f1():
print('123')
r=f1()
print(r)

Case execution result: 123, none

Case 5: python transmits a reference instead of a copy. The following li has been referenced after being executed by the function body.

Def f1 (a1 ):
A1.append (999)
Li = [11,22, 33,44]
Print (li)
F1 (li)
Print (li) # Because li has been executed, li is a new value. The parameter is passed as a reference, not a copy.

Execution result:

[11, 22, 33, 44]

[11, 22, 33, 44,999]


4) function parameters:

For example, f (x1, x2, x3 = 1), x1, x2, and x3 are parameters.

The parameter types include:

Common parameters: formal parameters and actual parameters

Default parameter: advance value, for example, x3

Specify parameters: You can change the order when calling the actual parameters.

Dynamic parameters:

* Args

** Kargs

Universal parameter * args, ** kagrs


Case 1: differentiated form parameters and actual parameters:

In this case, xxx is a formal parameter, and the actual parameter is passed when the function is called.

# Xxx here is a form parameter
Def f1 (xxx ):
Print ('20140901 ')
Return xxx + 'wee'

# Ggg here is the actual Parameter
R = f1 ("ggg ")
Print (r)


Case 2: Understanding the call of parameters

Common parameters, x1 and x2, are passed in sequence in f1

 
Def f1 (x1, x2 ):
Return x1 + x2
R = f1 ("ggg", "ccc") # Corresponds to x1 and x2 respectively in order

The default parameter. If this parameter is set, it must be placed after it, for example, x3.

Def f1 (x1, x2, x3 = "acb "):
Return x1 + x2 + x3
R = f1 ("ggg", "ccc") # x3 is not required here

Specify parameters. You can specify parameters in different order.

 
def f1(x1,x2,x3="acb"):
return x1+x2+x3
f1(x2="ggg",x1="ccc")
print(r)

Case 3: Dynamic Function (add * or ** before the function name): a formal parameter that can accept multiple actual parameters.

When the formal parameters include *, the passed parameters are placed in the group by default.

  • When the actual parameter is passed as a common parameter, even if the list is passed as an element

  • When the actual parameter * exists, all the elements in the list will act as each element of the ancestor.


def f1(*x):
print(x,type(x))
f1("55",66,"ll")
li=[11,22,33,"hhhh"]
f1(li)
f1(*li)

Execution result:

('55', 66,'ll ') <class 'tuple'>

([11, 22, 33, 'hhhh'],) <class 'tuple'>

(11, 22, 33, 'hhhh') <class 'tuple'>


If it is **, the default parameter is placed in the dictionary. The actual parameter must be a specified parameter or dictionary.

Case 4: If the form parameter is ** and the actual parameter is also passed **, the entire dictionary will be passed in.

def f1(**x):
print(x,type(x))
f1(n1="hh",n2="kk")
dic={'k1':'n1','k2':'n2'}
f1(**dic)

Execution result:

{'N1 ': 'hh', 'n2 ': 'kk'} <class 'dict '>

{'K1 ': 'n1', 'k2': 'n2 '} <class 'dict'>


Case 5: omnipotent parameter: f1 (* args, ** args), must be * Before, ** after

def f1(*a,**x):
print(a,type(a))
print(x,type(x))
f1(11,22,33,**{'k1':'n1','k2':'n2'})

Execution result

(11, 22, 33) <class 'tuple'>

{'K1 ': 'n1', 'k2': 'n2 '} <class 'dict'>


The application of universal parameters is str. format.

Case 6: Use placeholders to pass. This is an application of * arg.

#0 and 1 are placeholders, and the actual parameters are passed in order.
S1 = "I am {0}, age {1}". format ("hh", "2 ")
S2 = "I am {0}, age {1}". format (* ["hh", "2"])
Print (s1)
Print (s2)

Execution result:

I am hh, age2

I am hh, age2


Case 7: when the formal parameter is a character variable, the parameter must be specified later, which is an application of ** arg

s1="i am {name},age{age}".format(name="hh",age="2")
dic={'name':'nn','age':'4'}
s2="i am {name},age{age}".format(**dic)
print(s1)
print(s2)

Execution result:

I am hh, age2

I am nn, age4


5) global variables:Global, in uppercase. If you want to modify and apply the modification to the global, you need to add global

Case 1: global variables: the scope is global and in uppercase.

NAME = "hh"
Def f1 ():
Age = 18
Print (age, NAME)
Def f2 ():
Age = 19
Print (age, NAME)
F1 ()
F2 ()
Execution result:

Case 2: modify global variables: If you want to modify and use global variables, you can use global

NAME="hh"
def f1():
age=18
  global NAME
NAME = "hh3"
   print(age,NAME)
def f2():
age = 19
  print(age, NAME)
f1()
f2()

Execution result:

Case 3: Modify the global variable: if the global variable is not added, it only takes effect within the function.

NAME="hh"
def f1():
age=18
  NAME = "hh3"
  print(age,NAME)
def f2():
age = 19
  print(age, NAME)
f1()
f2()

Execution result:


6) three-element \ three-object operation:That is, the abbreviation of if... else.

Format: "result of true if condition else is false ",

"Condition? True_part: false_part"

Case 1: If the 1 = 1 condition is true, it is equal to the previous value. Otherwise, it is the subsequent value hhh.

If 1 = 1:
Name = "alex"
Else:
Name = "hhh"
# Abbreviation:
Name2 = "alex" if 1 = 1 else "hhh"

6) lambda functions: the purpose is to simplify the process of user-defined functions.

Case 1: lambda function, short function, a parameter

def f1(a1):
return a1+100
ret=f1(10)
print (ret)

# Use Cases can be abbreviated

f2=lambda a1:a1+100
r1=f2(19)
print(r1)

Case 2: lambda function, short for two parameters

F2 = lambda a1, a2: a1 * a2 + 100 # can also be the default value
R1 = f2 (19,10)
Print (r1)
Result: 290

Case 3: Apply lambda Functions

Words = [1, 2, 3, 4, 5, 6]
Key = lambda w: words [w]
R = key (2)
Print (r)
Execution result: 3

Case 4: cyclic usage case

word='the'
n=3
alphabet='uxyz'
s3=[word[0:i]+c+word[i+1:] for i in range(3) for c in alphabet]
print(s3)

The execution result is:

7) python has many built-in functions that can be directly used.

See: http://www.cnblogs.com/vamei/archive/2012/11/09/2762224.html


Case Link: Https://pan.baidu.com/s/1nvgivdn password: mvfc

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.