This article describes how to set and use function parameters in Python, and records differences between Python2.x and function parameters in Python3.x. For more information, see
1. parameters and shared references:
In [56]: def changer(a,b): ....: a=2 ....: b[0]='spam' ....: In [57]: X=1In [59]: L=[1,2]In [60]: changer(X,L)In [61]: X,LOut[61]: (1, ['
numbers in this list into strings:
Copy codeThe Code is as follows:>>> Map (str, [1, 2, 3, 4, 5])['1', '2', '3', '4', '5']>>>
You only need a line of code. Let's take a look at the exercises from Gu Xuefeng's python Tutorial: Use the map () function to change the nonstandard English names entered by users into uppercase letters and other standard names in lower case. Input: ['Adam ', 'lisa', 'bart'], and o
generated, the current state is logged, making it easier to generate data next time.
Use the generator function when the program requires higher performance or only one value to process at a time. Use a sequence when you need to get the value of a one-time set of elements.
This function is compiled into a generator function as long as there is a yield in the
an element from iterable and invokes function again with the result of the last call to function.The first call to function, if supplied with the initial parameter, calls function with the first element in iterable and initial as a parameter, otherwise the function is invok
].tb_frame.f_back
def findcaller (self):
"""
Find the stack frame of the caller so that we can note the source
File name, line number and function name.
"""
f = currentframe ()
#On Some versions of IronPython, Currentframe () returns None if
#IronPython isn ' t run with-x:frames.
If f is not None:
f = f.f_back
RV = "(Unknown file)", 0, "(Unknown function)"
While Hasattr (F, "F_code"):
CO = F.f_code
filename
first call to function f, we do not have enough values, C is not assigned, C will use the default value of 10.The second time the function is called, C is assigned a value of 1, and the default value is no longer used.3. Parcel deliveryWhen defining a function, we sometimes don't know how many arguments are passed when the call is called. At this time, the parce
like a=19. If the parameter is not eventually passed, the default value is used.Copy the code code as follows:def f (a,b,c=10):Return A+b+cPrint (f (3,2))Print (f (3,2,1))At the first call to function f, we do not have enough values, C is not assigned, C will use the default value of 10.The second time the function is called, C is assigned a value of 1, and the default value is no longer used.Parcel delive
It is no exaggeration to say that the use of function parameters in the Python language is the most flexible I have ever seen, and can do whatever you want, this article takes mathematical multiplication as an example to demonstrate several different types of communication:First, the default parametersdef multiply1 (x, y): return x * Yprint ("multiply1:", Multiply1 (2, 3))Output Multiply1:6, which is the
For the first time a friend of the Python programming language, just beginning to learn Python programming for
python function callThis aspect of the understanding is relatively small, in this article we will come to understand
how Python
Summary: Python's design core principle is simplicity--under the guidance of this principle, a lambda expression and a partial function are born: Both make function calls concise. This article mainly introduces you to the application of the partial function.
1. Why do I use a partial
statements are the best way to isolate external dependencies.
Use global variables with caution
The first consideration: global variables are often a way of communicating between crappy functions.It can cause problems with dependencies and timing, which can lead to difficulties in debugging and modifying the program. Second consideration: from code and performance optimizations, local variables are much faster than global variables. Based on the order in which
def more_arg(name,age,sex=' nan ',*agrs): #位置参数, default parameter, variable parameter, variable parameter will put the parameters of the subsequent passes to the args this tuple #当然args名字是随便写的, but in general we all write args. Print(name,age,agrs) more_arg(' Marry ', ', 'NV ',' python ', ' China')#调用
Keyword parameters:Keyword parameter use * * to receive, the following parameters are not fixed, want to write how
The reduce () function is also a high-order function built into Python. The reduce () function receives a parameter similar to map (), a function f, a list, but behaves differently from map (), and reduce () the incoming function
first domestic scope, call the end of the extinction 2, enclosing, nested function of the closure of the outer function of the namespace 3, global----, the interpreter exits 4, the build-in built-in module namespace, the interpreter starts to exit, Is the life cycle, print, open, etc.20. Function Execution Flow:1, the functi
default parameter in the original function [], which is essentially a list variable , will change with each use. This represents an empty list constant , which should be "L=none"If the number of inputs to the function is indeterminate, the variable parameter *args is used, and if the passed parameter is a dict type, the keyword argument should be used **kwThe former is to encapsulate multiple parameters in
( )#Output Result:# ANote: These cases are used for analysis and are seldom used in actual production.Scope:In Python, a function is a scope, and a local variable is actually placed in its scope.Age = 18deffunc1 (): Age= 22defFunc2 ():Print(age)returnFunc2#Func2 without parentheses, return this function nameVal=func1 ()Print(Val)#the name of the
maximum' else: print B, is maximum 'printmax (3, 4) # directly give literal valuesx = 5y = 7 printMax (x, y) # give variables as arguments
The running result is as follows:
4 is maximum7 is maximum
Working principle:
Here, we define a function called printMax, which requires two parameters, a and B. We use the if... else statement to find a large number of the two and print a large number.
In the use of the first printMax, we directly provide
‘:‘alex‘,‘age‘:333}{‘name‘:‘sun‘,‘age‘:363}
Example 2:#map # Merge Mappings
123
l=[1,2,3,4,5]res=map(lambdax:x**2,l)#求平列表里的平方值,并以列表的方式呈现print(list(res))
The execution results are:
1
[1,4,9,16,25]
Recursive functions:Definition: Inside a function, other functions can be called. If a function calls
(' C.sayhello ') Super (C,C). sayhe Llo () #调用C的类方法sayHello, super (C,C) proxy object, locate the direct parent Class B of C, and then call C's class method of the direct parent Class B SayHello, called when B's SayHello method calls B's direct parent Class A class method SayHello >>> C.sayhello () c.sayhellob.sayhelloa.sayhello# redefine Class C, inherit the same relationship, call the parent class method using Super (B,C) >>> Class C (B ): @classme
function). At this point, ITER creates an iterator object that is invoked each time the __next__ () method of the iterator object is called.If the return value of __next__ equals Sentinel, the Stopiteration exception is thrown, otherwise the next value is returned. Class Testiter (object): def __init__ (self): self.l=[1,2,3,4,5] self.i=iter (SELF.L) def __call__ ( Self): #定义了__call__方法的类的实例是可调用的 item
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.