A, PyCharm basic settings
1, with the mouse wheel Ctrl + - zoom in or out Font
Search zoom
2, in Windows Explorer to open a file or directory
Search keymap
Provided the button is not used, such as F3.
3, code hints
Search letter
Second, the custom function
1. Why use function
Function code write once, run many;
function allows code reuse, reduce code redundancy.
Tissue function is good, reusable, code segments used to implement a single, or the associated function.
Function module of the application can be improved, and code reuse. You already know that Python provides many built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.
Suppose I have such a demand:
But I still feel too much trouble, every time you want to eat at all times repeat this step. At this point, I hope to have such a machine:
The repetitive work package together, we just put something to the machine, you can get what we want.
This is the so-called code reuse.
example
# 定义方法
def print_nums():
"""此处是函数功能的描述"""
for i in range(1,11):
print(i,end=" ")
# 1.三角形 2.正方形 3.梯形
key = int(input('请输入要打印的图形:'))
if key == 1:
# 打印三角形的代码
print_nums()
pass
elif key == 2:
# 打印梯形的代码
pass
elif key == 3:
# 正方形的代码
pass
Output:
请输入要打印的图形:1 1 2 3 4 5 6 7 8 9 10 进程已结束,退出代码 0
Analyze
2. Defined Functions
You may want to define a function by their own functions, the following simple rules:
Keywords: def
Function block def keyword beginning, followed by the name and function identifier parentheses (), at the end by a colon.
The first line in the function usually write notes meaning, the name of the function table
Note After a blank line, began to write code blocks, code libraries to indent
Any incoming parameters and arguments must be placed in the middle of parentheses. Between parentheses may be used to define the parameters.
The first statement function can be selectively used documentation string - for storing function instructions.
Start function contents colon, and indentation.
return [Expression] End function, selectively returns a value to the caller. return without an expression equivalent to return None.
After the function, empty 2 lines
1 empty line after the function call, and then the implementation of other Code
grammar
#代码如下
def functionname( parameters ):
"函数_文档字符串"
function_suite
return [expression]
By default, the parameter name and the parameter value is defined as a function of the order of declaration match up.
Third, the function type
Python function parameter types can be used:
Mandatory parameter
named parameters
default parameters for
variable length parameters
-
Parameter Type:
- 1, positional parameters: a location parameter (sequence) is important, the number of parameters and arguments shaped to match
- 2, keyword arguments: not very strict requirements for the position parameters
- 3, the default value of the parameter:
- (1) If the default parameter value is specified in the argument may not deliver the parameter corresponding to the argument
- (2) If the default parameter value is specified, after transmission of the summary parameter arguments, parameters passed ultimately prevail argument
- 4, variable length parameters:
- (1) * a: receiving a transmitted single value, stored tuple
- (2) ** b: receiving a key parameter of the form, save for the dictionary format
1, no function parameter
No reference function implementation and call:
# 定义无参函数
def say_hi():
"""介绍自己的函数"""
print('我是xgp,今年18岁,年收入xxxx元')
# 调用无参函数
say_hi()
Output:
我是xgp,今年18岁,年收入xxxx元 进程已结束,退出代码 0
2, parameterized function
Here to talk about the function arguments:
- Parameter: it refers to the formal parameters, virtual, do not take up memory space when allocating memory unit parameter unit only to be called
- Argument: refers to the actual parameter is a variable, the memory space occupied, the one-way data transfer, passed parameter arguments, parameters, arguments can not pass
example
# 定义带参函数:形参(形式参数,模板)
def say_hi(name,age,money):
"""介绍自己的函数"""
print('我是'+name+',今年'+str(age)+'岁,年收入'+str(money)+'元。')
# 调用带参函数:实参(实际传递的参数)
say_hi('xgp',20,20000)
Output:
我是xgp,今年20岁,年收入20000元。 进程已结束,退出代码 0
Note: When you call the function, the number of arguments passed
to the formal parameters consistent |
(1) position parameter
As can be seen from the above example, the parameters and the actual parameters in the form of one to one, if the exchange position, x and y being called, will exchange positions, as follows:
def test(x,y):
print(x)
print(y)
print("--------互换前-----")
test(1,2)
print("--------互换后-----")
test(2,1)
#输出
--------互换前-----
1
2
--------互换后-----
2
1
Because the definition of x, y two parameters, so when passing arguments, passing only two arguments, one more or less a problem are:
a: a multi-transfer parameters
def test(x,y):
print(x)
print(y)
print("--------多一个参数----")
test(1,2,3)
#输出
--------多一个参数----
Traceback (most recent call last):
File "D:/PycharmProjects/pyhomework/day3/函数_带参数.py", line 8, in <module>
test(1,2,3)
TypeError: test() takes 2 positional arguments but 3 were given #test()函数需要传两个实参,你传了三个实参
b: at least one argument passed
def test(x,y):
print(x)
print(y)
print("--------少一个参数----")
test(1)
#输出
--------少一个参数----
Traceback (most recent call last):
File "D:/PycharmProjects/pyhomework/day3/函数_带参数.py", line 8, in <module>
test(1)
TypeError: test() missing 1 required positional argument: 'y'
#没有给y参数传实参
(2) keyword arguments
The above positional parameters, looks a bit dead, must be formal and actual parameters of the position correspondence, otherwise it will pass the wrong parameters, in order to avoid this problem, there is a play key parameters: Keyword not need to pass parameters one to one, you only need to specify which of your parameter which arguments can be invoked;
def test(x,y):
print(x)
print(y)
print("--------互换前------")
test(x=1,y=2)
print("--------互换后------")
test(y=2,x=1)
#输出
--------互换前------
1
2
--------互换后------
1
2
3, the default parameters
The function is called, the default value if no incoming parameters is considered to be the default. Under regular printing the default age, if age is not passed:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#可写函数说明
def printinfo( name, age = 35 ):
"打印任何传入的字符串"
print "Name: ", name
print "Age ", age
return
#调用printinfo函数
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Output:
Name: miki Age 50 Name: miki Age 35
4, variable length parameter
You may need a function that can handle more parameters than the original statement. These parameters, called variable length parameters, and the two kinds of different parameters, not naming declaration. The basic syntax is as follows:
def functionname([formal_args,] *var_args_tuple ):
"函数_文档字符串"
function_suite
return [expression]
* Added an asterisk ( ) variable name stores all variables unnamed parameters. Examples of variable-length parameters as follows: **
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 可写函数说明
def printinfo( arg1, *vartuple ):
"打印任何传入的参数"
print "输出: "
print arg1
for var in vartuple:
print var
return
# 调用printinfo 函数
printinfo( 10 )
printinfo( 70, 60, 50 )
Output:
输出: 10 输出: 70 60 50
(1) Examples
# 不定长参数的类型
def no_test(*args,**b):
print((args))
print(b)
no_test(1,2,3)
no_test(name='test',ages=18)
Output:
(1, 2, 3) {} () {'name': 'test', 'ages': 18}
5, an anonymous function
python using lambda to create an anonymous function.
- Just a lambda expression, function body is much simpler than def.
- Lambda expression is a body, instead of a code block. We can only package a limited logic into the lambda expression.
- lambda function has its own namespace, and can not be accessed outside of its own argument list or the global namespace parameters.
- Although lambda function looks can only write a single line, but not equivalent to C or C ++ inline functions, which aims not take up the stack memory when calling small functions to increase operating efficiency.
grammar
Lambda function syntax contains only one statement, as follows:
lambda [arg1 [,arg2,.....argn]]:expression
Following examples:
相加后的值为 : 30
相加后的值为 : 40
Four, rerun the type of data transfer list
return statement [Expression] to exit the function returns a selective expression to the caller. return statement with no parameter values return None. No previous example demonstrates how to return a value, the following example will show you how to do it:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 可写函数说明
def sum( arg1, arg2 ):
# 返回2个参数的和."
total = arg1 + arg2
print "函数内 : ", total
return total
# 调用sum函数
total = sum( 10, 20 )
Output:
函数内 : 30
Note: do not write a return statement within a function, the default is to return an empty object. That it is, even if I did not write, internal python also done a deal.
At this time, some people can not tell the difference between the output of the function return value.
So to speak, in the print function in the operation of such content can be output, because, although the execution environment functions are independent, but the code is valid. An external operation can be performed, the function may be internal. But not all functions are so obvious after the implementation of the output, then we need to see if the function is successful, or that I put rice into it, you always take a meal after a round operation to me. Come on.
This is the meaning of function return. It returns an object. This object may be a description of the execution state, or may be the result of processing and the like.
1, return statement returns a simple type
def test():
return 'hello'
print(test())
# return 语句返回字典
def show_info(name,age):
person = {'name':name,'age':age}
return person
print(show_info('test',18))
Output:
{'name': 'test', 'age': 18} 进程已结束,退出代码 0
2, the user greetings
def say_hi(first_name,last_name):
"""返回完整名字"""
full_name = first_name + ' ' + last_name
return full_name
while True:
print('请输入您的姓名:')
f_name = input('姓:')
if f_name =='q':
break
l_name = input('名:')
if l_name == 'q':
break
# 调用函数
format_name = say_hi(f_name,l_name)
print('hello'+format_name+'!')
Output:
请输入您的姓名: 姓:x 名:gp hellox gp!
3, data transfer list type
def test(names):
for name in names:
print(name)
user_name = ['sdf','fsd','fewfwef','fwefe']
test(user_name)
Output:
sdf fsd fewfwef fwefe 进程已结束,退出代码 0
5, practice range function
- When only one function call variable, this variable is the arithmetic mean of the output end of the series, such as
range(5)
- When given two variables, refer to the start and end points as output ,,
range(2, 5)
- When given three variables, on the basis of the time of a variable refers to the first three output step, such as
range(2, 5, -1)
(Always assuming that integer or floating point when we call this function)
Analyze how to achieve this function, giving my ideas below as a reference
- Needs a total of three parameters are obvious;
- The most intuitive feeling is that the start value is to have a default value, if not specified where to start, start from 0;
- Step is to have a default value, if not specified, then the step size is 1;
- According to have default values of the parameters to be placed behind the principle, then the most natural design parameters
range_custom(stop, start=0, step=1)
- This program looks feasible, but does not meet the requirements of just two behind, so if we use two variables called, the start and end points are reversed;
- We add a judgment on it, if start with an initial value, then that we call only gave one argument, this time to stop is the end, if the start was reassigned explanation given at least two parameters, then this time the value of the stop and start the exchange about it;
- Now this function seems to be satisfactory for most situations, but there is a bug, if given the time to the start of the given parameter value 0 is how to do it? As
range_custom(-5, 0)
under the current rules will be translated intorange(0, -5)
, but our purpose isrange(-5, 0)
; - Therefore, the initial value of the start should not be anything else but a digital data types, for convenience, we call it the initial value assigned to
None
our program template came out.
def range_custom(stop, start=None, step=1):
if start is None:
return range(stop)
return range(stop, start, step)
Now the program has met our requirements, but do not look very comfortable, can be changed
def range_custom(start, stop=None, step=1):
if stop is None:
return range(start)
return range(start, stop, step)
Now the parameters of this function in order to better understand some of the logic, we can say that basically meet the requirements. Of course, the present embodiment only to illustrate the order parameters of the problem, not in order to achieve the range function. In fact Python also includes knowledge of the range function parameters instantiation, generators, etc., at the back we should have another chance to touch it.
Optional parameters
When it comes to optional parameters, some people may have seen, they do not understand in the end what it meant, it is generally like this occur
def func_option(*args):
return args
* Note that we declare a function of time added a `before the parameter name ` asterisk, which is an optional parameter declaration method. Then the optional parameters in the end what use is it? **
Optional parameter is the role of tuple that all extra variables collected, the name of the tuple is the optional parameter name. In the above example func_option
, we can call it with any number of variables, such as a = func_option(1, 2, 3)
it a
would be a tuple (1, 2, 3)
. Why on tuple instead of a list, we are on a Python Advanced - simple data structures mentioned, the tuple is often more than a list of priority data structures used in Python, the specific reasons after this article by in-depth self defined function parameters section will be discussed.
We just said optional parameters will collect extra variables. I say this for a reason.
>>> def func_option(a, *args, c=2):
... return args
...
>>> func_option2(1)
()
>>> func_option2(1, 2)
(2,)
>>> func_option2(1, 2, 3)
(2, 3)
* Noticed that our ` args` the value addition to the ordinary other than the first variable parameters are placed in the tuple. Doing so leads to a problem is that we have a parameter default values if you do not call the given parameter name, then it can only ever use the default value. And not to have the default parameter values on the final program will face an error if we call the function. **
>>> func_option2(c=1, 2, 3)
File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument
Is there a good way to avoid this problem? We can try to put on the back of optional parameters have default parameter values.
>>> def func_option3(a, c=2, *args):
... return args
...
>>> func_option3(1)
()
>>> func_option3(1, 2)
()
>>> func_option3(1, 2, 3)
(3,)
>>> func_option2(c=1, 2, 3)
File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument
So this form of function can not solve the problem before it. It seems not, but we know, call a function of time, to try to have default values of the parameters in the rearward position to the variable. So in the end we both which method is the use? In practice, we tend to put optional parameters after the parameters that have default values, but if many parameters, we tend to call the function when all variables will add the parameter name. And practice, in fact, optional parameters used not by much, relatively speaking, an alternative argument in fact is more interesting. This optional parameter is typically in the form of
def func_optionkw(**kwargs):
return args
In this case, the keywords are optional parameters as key-value pairs stored in the parameter name in the dictionary. That is, when the function is called after the meet the general parameters, variables should be given in the form of an assignment statement, the left side of the equal sign as the key to the right as the value. Failure to do so will the error.
>>> func_optionkw(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: t2() takes 0 positional arguments but 1 was given
It should be noted that a custom function only one optional parameter, but can also have up to a keyword argument. After which keywords should be placed in the general parameters of optional parameters.
Now we come to sum up the general rules of the order of function parameters:
- General parameters on the front
- Optional parameters on the final surface
- Optional keyword parameters on the back of the general optional arguments
- Try to have default values of the variable parameters corresponding to the rearward position in the function call
- If the argument is more, the function is called, the best all variables specified parameter name
These, in order to prevent mistakes when some function definitions, some to prevent errors when the function is called, in short, should develop good programming habits.
Fifth, variable scope
All the variables of a program is not in any position can access. Access depends on where the variable is assigned.
Scope of a variable determines which part of a program in which specific variable names you can access. Two basic variable scope as follows:
- Global Variables
- Local variables
Sixth, global and local variables
It is defined as having a local scope, defined outside the function has global scope within a function of the variables.
The local variables can be declared within its access function, and can access the global variables in the entire program range. When you call a function, all variables declared within a function name will be added to the scope. Following examples:
Example (Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
total = 0 # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
#返回2个参数的和."
total = arg1 + arg2 # total在这里是局部变量.
print "函数内是局部变量 : ", total
return total
#调用sum函数
sum( 10, 20 )
print "函数外是全局变量 : ", total
Output:
函数内是局部变量 : 30
函数外是全局变量 : 0