Python's ternary operations, sets, functions

Source: Internet
Author: User
Tags function definition

Tag:echo    number     Global variables    .com    list     money   mod    format     presence    

The one or three-dollar operator ternary operator can be evaluated directly when assigning variables, and then the assignment format: [on_true] if [expression] else [on_false]res = value 1 if condition else value 21. Example: a =1b = 2c= a If a>1 else b #如果a大于1的话, c=a, otherwise c=b  if the ternary operator is not used, it is judged by the If-else condition as follows: A = 1b = 2if a >1:c = Aelse:c = b 2. Ternary operators can also be used In the list and dictionary example: 1-10 of the number, print out the even ternary operations: ss = [I for I in range (1,11) if i%2==0] #循环1-11 values (excluding 11), if the value can be divisible by 2 (that is, the number of even), Write to SS in this list print (ss) #最终打印结果 [2, 4, 6, 8, 10] if-else condition s = []for i in Range (1,11): If I%2==0:s.append (i) print (s) &n bsp;  set: Set holds a series of elements, and the list is very similar, but also a data type, but set of elements are not duplicated, and is unordered features: Set does not contain duplicate elements (natural deduplication) and disorderly  2. Definition of a collection a. Define a list, define the collection by casting nums = [1,1,2,3,5,6,77,8]num_set = Set (nums) B. Direct definition num_set1={1,2,3,3,4} The collection cannot access the element by subscript   3. Loop through sets = Set ([' Adam ', ' Lisa ', ' Bart ']) for name in S:print (name) Result: Lisabartadam 4. add element s = {1,2,3}s.add (4) Print ( s) #结果 {1, 2, 3, 4} s.update ([333,444,333]) s.update ({56,78,999})  5. Delete element S.remove (333) #删除元素, If the element does not exist, it will error S.pop () #删除一个随机的元素, and return the deleted element S.discare (111) #如果删除的元素存在, delete, do not exist do not handle    three, function 1. What is a function? Defined: A function is to encapsulate a set of statements by a name (function name), and to execute the function, simply call the name of its functions.  2. Benefits of using Functions A. Simplifying code B. Improving the reusability of code c. Code extensible  3.python function Definition def functionname (parameters): Function_suite return [ Expression] Description: def is the keyword, followed by the function name, function name can not be repeated, the content in parentheses is a parameter, according to the actual situation, define the number of arguments you need function_suite to return the function body returns the value if you do not write the return line, The default return is none 4. function call def hello ():p rint (' hello! ') Hello () #函数调用, the function is called in the way that the function name is followed by the parentheses  5. Parameters and argument functions can be passed in when called, both physical and argument: The shape parametric allocates the memory unit only when it is called, and immediately releases the allocated memory unit at the end of the call. Therefore, the formal parameter is only valid inside the function.   Arguments: Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and in the case of a function call, they must have a definite value in order to pass these values to the parameter. The parameter variable can no longer be used after the function call finishes returning the keynote function.  6. Four parameter types of the function's parameter type function: Positional parameter, default parameter, indefinite length parameter, keyword parameter position parameter: Position parameter, is the parameter's position to pass the argument example: Def reg (Name,age):p rint (' Hello%s,age is% S '% (name,age)) #name, age is a required parameter, position parameter reg (' HHF ', 27) Description: There are several positional parameters at the time of the call to pass a few, otherwise will be error if there are multiple positional parameters, but can not remember the location of the parameters, You can use the name of the positional parameter to specify that the call is a specific call to Reg (Name= ' Huihui ', age=25), which is called the keyword argument   default parameter: The default parameter is to assign a value to the function by default when defining formal parameters, the default parameter is not required, If you pass a value to the default parameter, it will use the value you passed in. If the default value parameter is used, it must be placed after the position parameter definition   Example: Def reg (name,age,sex= ' man '):p rint (' Hello%s,age is%s '% (name,age)) #name, the age is a required parameter, Positional parameters #sex是默Recognition parameter, not a required parameter reg (' HHF ') #不传sex, sex uses the default value parameter, sex= ' Male ' reg (' Huihui ', 28, ' female ') #给sex传值, sex= ' women '   Non-fixed parameters: The above two positional parameters and the default parameters are the number of parameters is fixed if there is a function, the parameters are not fixed, do not know what the function will expand into what kind of, perhaps more and more parameters, this time if the use of fixed parameters, the subsequent program is not good extension, At this time, you can use non-fixed parameters have two kinds of non-fixed parameters, one is a variable parameter, one is the key parameter variable parameter: variable parameter with * to receive, after the number of arguments to pass how many, if the positional parameters, default parameters, variable parameters used together, The mutable parameter must be behind the positional and default values parameters. Variable parameters are also non-mandatory. Example: Def post (*args):p rint post (' 001 ', ' Denglu ', ' http://www.baidu.com ', post,a=1) post () Description: Variable parameter, also called parameter group, is not required, It receives a tuple it calls the function simultaneous into each parameter into a tuple   keyword parameter: keyword parameter use * * to receive, the following parameters are not fixed, want to write how many write how many, of course, can also be used with the above several, if you want to use together, The keyword parameter must be in the last face. Using keyword parameters, you must use the keyword argument, the keyword parameter is also a non-mandatory example: def kw (**kwargs):p rint (Kwargs) kw () kw (Age=18,name= ' aaa ') d={' age ':, ' name ' : ' AAA '}kw (**d) Description: Keyword parameter, received is a dictionary, call with xx=11, is not required to enter the dictionary call when you have to write **{' age ': ' AAA '}  other examples: def other2 (name , country= ' China ', *args,**kwargs):p rint (name) print (country) print (args) print (Kwargs) other2 (' HHF ') other2 (' Niuhui ') , ' Beijing ', ' python ', ' changping ', user= ' niu ') Description: If required, default, variable, and keyword parameters must be received in the order of required parameters, default value parameters, variable parameters, and keyword parameters. Otherwise an error will be  def write (FilenaMe,model,ending,user,os,money,other):p rint (filename) print (model) print (ending) print (user) print (OS) print (money) Print (Other)  write (os= ' Windows ', user= ' wubing ', model= ' W ', filename= ' a.tx ', ending= ' UTF8 ', money=9999,other= ' xxx ')-#write (os= ' windows ', ' a.txt ') #位置参数调用参数必须在关键字调用前, otherwise error write (' A.txt ', ' w ', ' gbk2312 ', ' HHF ', os= ' Windwos ', money= 9999,other= ' xxx ')  7. function return value def plus (A, b): C=a+breturn C Description: A function encounters a return, immediately ends the function B after the function is called, return the result of the calculation C function can not return a value, If there is no return value, the default return is None, if the function's processing results we need to use elsewhere, we have to give the function a return value if the function returns multiple values, then it will put a number of values in a tuple to  score1 = 50score2 = 90def Echo (): Return score1,score2 8. Local variables and global variables local variables: In the local variable, the scope of the variable, the variable is invalidated by the global variable: in the entire program is effective, The first definition in the program is the global variable-# score3 = [1,2,3,4,5]-# score3 = {"id": 1}score3 = 100def My_open (): FW = open (' A.txt ', ' A + ') Fw.seek (0) Prin T (' Score3 ', score3) d={' id ': 2}d[' price ']= 99 Description: A. The definition of a variable inside a function is called a local variable, it can only be used inside the function, out of the function, you can not use B. Variables defined outside the function are global variables, and C can also be used within a function if you want to modify the value of a global variable inside a function, Then you have to use the Global keyword to declare that you want to modify the global variable is int, string, you must write global if it is a dictionary and list, if you want to modify, you cannot add global

Ternary operations, collections, functions of Python

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.