Bowen structure
Custom function
Variable scope
Python built-in functions
I. function
Functions in Python are collections of statements and expressions. There is no limit to the use of functions, just like other values in Python. For reusable code, you need to write a custom function for reuse.
Functions can be divided into nonparametric functions and parametric functions
1. Nonparametric function
It is not complicated to define a function without parameters. The syntax format is as follows:
def function name (): Code block return [expression]
Case study:
def add(): \\Defined function op1=10 op2=20 rt=op1+op2 print op1,'+',op2,rt return add() \\Calling function \\Output result >>> 10 + 20 30 >>>
Case: output 99 multiplication table
def nineMultiTab(): op1=(1,2,3,4,5,6,7,8,9) op2=(1,2,3,4,5,6,7,8,9) for i in op1: for j in op2: print i,"*",j,"=",i*j retrun nineMultiTab() \\Output result >>> 1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 1 * 4 = 4 1 * 5 = 5 1 * 6 = 6 1 * 7 = 7 1 * 8 = 8 1 * 9 = 9 2 * 1 = 2 2 * 2 = 4 ..................slightly
(2) when using a function, you often make some mistakes, which are summarized as follows
The definition of a function precedes the call of a function, or an error will occur.
The code of the function body is a whole. Pay attention to indentation.
A colon is used when defining a function, but not when calling.
2. Parameters with parameters
The syntax format of the function with parameters is as follows:
def function name (list of formal parameters): Code block return [expression]
Case study:
def add(x,y): \\Function definition with parameters return x + y print add(1,2) \\Function call with parameters \\Output result >>> 3
(1) when the program is cumbersome, it is difficult to remember the order of parameters. You can use keyword parameters. When calling a function, the keyword parameter specifies which parameter the parameter value is assigned to. The syntax format is as follows:
Function name (parameter 1 = parameter 1, parameter 2 = parameter...)
Comprehensive case: (calculator)
def operator (op1,op2,opFu): if opFu not in '+-*/': return -1 if opFu == '+': result = op1+op2 elif opFu == '-': result = op1 - op2 elif opFu == '*': result = op1*op2 elif opFu == '/': if op2 == 0: print 'Error, divisor cannot be 0' result = None else: result = op1 / op2 return result def convert(op): flag = True for ch in op: if ch not in '1234567890': flag = Flase brank if flag == True: return int(op) else: return None if __name__== '__main__': str1 = 'Please enter the first number:\n' strFu = 'Please enter an arithmetic operator:\n' str2 = 'Please enter 2 numbers:\n' while True: print 'You need to exit the program. Please enter a letter q' opp1 = raw_input(str1) ch = opp1.strip()[0].lower() if ch =='q': break op1 = convert(opp1) if op1 ==None: print 'Input error, please input integer!/n' continue while True: opFu= raw_input(strFu) if opFu in '+-*/': break else: print 'Operator input error' continue while True: op2 = convert(raw_input(str2)) if op2 == None: print "Input error, please input integer!\n" continue else: break result = operator(op1,op2,opFu) if result <> None: print "Calculation%d %s %d = %d\'n" %(op1,opFu,op2,result) print 'Program exited' \\The output is as follows //To exit the program, enter the letter q //Please enter the first number: 20 //Please enter an arithmetic operator: * //Please enter 2 numbers: 30 //Calculation 20 * 30 = 600'n //To exit the program, enter the letter q
II. Variable scope
Scope refers to the application scope of variables in the program, and the position of variable declaration determines its scope. Python distinguishes local variables and global variables according to scope. Global variable means that the variable at the highest level in a module has a global scope. Unless it is deleted, it will survive until the end of the program, and all functions can access the global variable.
Local variable refers to that the variable defined in the function has a local scope, which depends on whether the function that defines the variable is active at this stage. When the function is called, the local variable is generated and exists temporarily. -Once the function is executed, the local variables will be released. The scope of a local variable is limited to the functions that define it, and the scope of a global variable is visible within the entire module. Local variables with the same name are not allowed in the same function. In different functions, you can have local variables with the same name. In the same program, when the global variable and the local variable have the same name, the local variable has a higher priority.
The following code shows the usage of local and global variables:
def addAge(age): age +=1 print 'addAge(): _age=%d age=%d' %(_age,age) return age _age = input('Input age: \n') rt = addAge(_age) print 'main(): _age =%d ' %_age print 'main(): rt=%d' %rt \\The output is as follows >>> //Enter age: 20 addAge(): _age=20 age=21 main(): _age =20 main(): rt=21 >>>
Local variables can only be used in local areas. Other areas cannot be accessed. For example, age is a local variable. It cannot be referenced in global areas, such as adding code at the end of a program
-
lambda function
The function of lambda is to create anonymous function, which is a special way to declare function.
The syntax of the lambda function is as follows:
lambda params: expr
params is the list of parameters received by the function, and expr is the expression of the return value of the function.
The common function and a lambda function are as follows:
def sum1(x,y): \\Ordinary function return x+y sum2 = lambda x,y : x+y \\lambda function print sum1(3,4) print sum2(3,4) \\The output is as follows >>> 7 7
- Built in function
In addition to its own syntax structure, python provides commonly used built-in functions. Built in function is a method often used by programmers. It can increase the efficiency of programming. For example, float() is a built-in function. Built in functions are automatically loaded and recognized by the Python interpreter. It does not need to import the module, does not need to do any operation. It can be called without reference.
(1) abs() function can return the absolute value of a number, that is, a positive number. The syntax format is as follows:
abs (x)
Case study:
>>> abs(10) 10 >>> abs(-10) 10 >>> bb = -3 >>> abs(bb) 3
(2) the return value of the bool() function is True or False. It is a shorthand for Boolean. The syntax format is as follows:
bool([x]
Case: it cannot be empty
>>> bool() False >>> bool(0) False >>> bool(-3) True >>> bool('xws') True
(3) the float() function is used to convert data to float type. The syntax format is as follows:
float([ x ])
Case study:
>>> float('25') 25.0 >>> float(3) 3.0 >>> float(999.123) 999.123 >>>
Both string and number can be converted to float type, if not, an exception will be thrown.
(4) the int() function can convert data to integers. The syntax structure is as follows:
int ([ x [,base]])
Case study:
>>> int(199.99) \\Floating point number 199 >>> int('100') \\Character string 100 >>> int('99.9') \\Character string Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> int('99.9') ValueError: invalid literal for int() with base 10: '99.9' >>>
It should be noted that when the parameter is a string, the string can only be in integer format. If it is a floating-point format, an exception will be generated.
(5) the range() function can generate a list. The syntax structure is as follows:
range ([start,] stop[,step])
Case study:
>>> range(0,5) [0, 1, 2, 3, 4] >>> range(0,30,3) [0, 3, 6, 9, 12, 15, 18, 21, 24, 27] \\Increase progressively >>> range(30,0,-3) [30, 27, 24, 21, 18, 15, 12, 9, 6, 3] \\Decrement >>>
(6) sum() function can sum the elements in the list. The syntax structure is as follows
sum(x[ ,start] )
Case study:
>>> num=range(0,500,50) >>> num [0, 50, 100, 150, 200, 250, 300, 350, 400, 450] >>> print(sum(num)) 2250 >>>
(7) the max() function can return the largest element in a list, tuple or string. The syntax structure is as follows:
max (x)
Case study:
>>> num=[6,2,12,7,64] >>> max(num) 64 >>> string ='d,u,a,n,g,D,U,A,N,G' >>> max(string) 'u' >>>
The len() function returns the length of an object. The syntax format is as follows:
len(s)
case
>>> len('duang') \\Character string 5 >>> aa=['python','jave','c#','vb'] \ \ list >>> len(aa) 4 >>> bb={'zhangsan':'100','lisi':'90'} \\Dictionaries >>> len(bb) 2