In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
Blog structure
Custom function
Variable scope
Python built-in function
one。 Function
Functions in Python are all collections of statements and expressions. There is no limit to the use of functions, just like other values in Python, and code that is reused needs to be written as a custom function to facilitate reuse.
Functions can be divided into functions without parameters and functions with parameters.
1. No-parameter function
Customizing a no-parameter function is not complicated, and the syntax format is as follows:
Def function name (): code block return [expression]
Case study:
Def add ():\\ define function op1=10 op2=20 rt=op1+op2 print op1,'+',op2,rt returnadd ()\\ call function\\ output result > 10 + 20 30 >
Case: output ninety-nine multiplication table
Def nineMultiTab (): op1= (1, for j in op2, 3, 5, 5, 6, 7, 8, 9) op2= (1, 2, 3, 4, 4, 5, 6, 7, 8) for i in op1: for j in op2: print I, "*", j, "=" 1 * 1 = 11 * 2 = 21 * 3 = 31 * 4 = 41 * 5 = 51 * 6 = 61 * 7 = 71 * 8 = 81 * 9 = 92 * 1 = 22 * 2 = 4. Slightly
(2) one or some mistakes are often made when using functions, which can be summarized as follows.
The definition of the function should precede the call to the function, otherwise there will be an error.
The code of the function body is a whole, so you should pay attention to indentation.
Use colons when defining functions, but not when calling them.
two。 Parameter
The syntax format of the function with parameters is as follows:
Def function name (formal argument list): code block return [expression]
Case study:
Def add (XMagi y):\\ define return x + yprint add with parameters\\ function calls with parameters\\ output results > 3
(1) when the program is cumbersome, the order of parameters is difficult to remember, and keyword parameters can be used. The keyword parameter specifies which parameter the parameter value is assigned to when calling the function. The syntax format is as follows:
Function name (formal Ref 1 = argument 1, formal Ref 2 = argument.)
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 The divisor cannot be 0 'result = None else: result = op1 / op2 return resultdef convert (op): flag = True for ch in op: if ch not in' 1234567890: flag = Flase brank if flag = = True: return int (op) else: return Noneif _ 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' need to exit the program Please enter the letter q' opp1 = raw_input (str1) ch = opp1.strip () [0] .lower () if ch = = 'Qothers: break op1 = convert (opp1) if op1 = = None: print' input error, please enter an 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 enter the integer!\ n "continue else: break result = operator (op1,op2,opFu) if result None: print" to calculate% d% s% d =% d\'n "% (op1,opFu,op2,result) print 'program exited'\\ output result is as follows Please enter the letter Q Please enter the first number: 20 Please enter an arithmetic operator: * Please enter 2 numbers: 30 to calculate 20 * 30 = 600 n need to exit the program, please enter the letter Q two. Variable scope
Scope refers to the scope of application of variables in the program, and the location of variable declaration determines its scope. Python distinguishes local variables and global variables according to scope. Global variable means that the highest-level variable in a module has a global scope and survives until the end of the program unless deleted, and all functions can access the global variable.
Local variable means that the variable defined in the function has 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 variable will be released. The scope of a local variable is limited to the function that defines 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, there can be 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 higher priority.
The following code demonstrates the use 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'% _ ageprint' main (): rt=%d'% rt\\ output results are as follows > > input age: 20addAge (): _ age=20 age=21main (): _ age=20 main (): rt=21 >
Local variables can only be used locally, other scope is not accessible, such as age is a local variable. It cannot be referenced in the global scope, such as adding code at the end of the program
Lambda function
The purpose of the lambda function is to create anonymous functions, which is a special way to declare functions.
The syntax of the lambda function is as follows:
Lambda params: expr
Params is equivalent to the list of parameters received by the function, and expr is the expression of the value returned by the function.
An ordinary function and a lambda function. The example is as follows:
Def sum1 (XMagol y):\\ ordinary function return x+ysum2 = lambda XMagi y: XQuery\\ lambda function print sum1 (3pr 4) print sum2 (3pr 4)\\ output results are as follows > 77 built-in functions
In addition to its own syntax structure, Python also provides commonly used built-in functions. Built-in functions are methods often used by programmers. Can increase the efficiency of programming, such as float () is a built-in function. Built-in functions are loaded automatically and can be recognized by Python's interpreter. It does not need to import the module and does not have to do any operation. It can be called without a reference.
(1) the abs () function returns 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 bool () function is True or False. It is an abbreviation for Boolean (Boolean value) and 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 strings and numbers can be converted to float, and if not, an exception is 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 > int ('100')\\ string Traceback (most recent call last): File ", line 1, in 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, there will be an exception.
(5) the range () function can generate a list with the following syntax structure:
Range ([start,] stop [, step])
Case study:
> > range (0jue 5) [0,1,2,3,4] > > range (0meme30pyr3) [0recedence 3,6,9,12,15,18,21,24,27]\ increment > > range (30meme 0mam 3) [30, 27, 24, 21, 18, 15, 12, 9, 6, 3]\ decrease >
(6) the sum () function can sum the elements in the list. The syntax structure is as follows.
Sum (x [, start])
Case study:
> num=range (050,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, num, 12] > max (num) 64 > > string ='d string, a, g,
The len () function returns the length of an object in the following syntax format:
Len (s)
Case
> len ('duang')\\ string 5 > aa= [' python','jave','c#','vb']\\ list > len (aa) 4 > bb= {'zhangsan':'100','lisi':'90'}\\ Dictionary > len (bb) 2
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.