Python Learning notes a better blog http://www.cnblogs.com/BeginMan/p/3192695.html preface:
Since 2016/05/15, we have been learning python for 2.5 months, and then started to learn about data analysis techniques such as crawlers, and the goal is to automate the download of the tweets that are forwarded to individuals via Python.
Python implements code chunking by indentation, and all of this article uses the TAB key to indent
It is best to separate the different indentation modules with spaces to ensure the readability of the code.
0 or one little things
1. print ' test ' prints line breaks by default, and if you don't want to wrap, you can add a comma after the statement to eliminate line breaks. print ' Test ',
The 2.python statement can be either a semicolon-terminated or no-add, but it must be added when writing multiple statements on a single line. It is not recommended to use semicolons.
3. Indentation at the beginning of a line is a must, and a statement with the same indentation is called a block. You cannot use the mixed indentation of tabs and spaces, which can cause cross-platform problems, and all subsequent indents are tab keys
I. Basic introduction objects, variables, identifiers, operators, precedence of operations, etc. 1.1. Number in Python there are 4 types of books: integers (int), long integers, floating-point numbers (float), complex numbers 1.2. Single quotes, double quotes, three quotation marks, and double quotation marks are applied exactly the same way, preserving the space in the string and the tab three quotation marks: "" "" "" "" ", in three quotation marks you can arbitrarily quote single and double quotation marks. For example, two people can use the three quotes 1.3. Escape character escapes some special characters to indicate that a single backslash escape at the end of a line is not escaped, but rather that the string continues on the next line instead of a new row. When parentheses, brackets, or curly braces are used, the code between the front and back brackets is automatically considered a logical line, and the line break does not require a backslash for example: "This is the first sentence.\this is the second sentence." Represents a string of 1.4 natural strings if you want to represent some special strings that are not escaped processing, you need to prefix R or R in front of the string to represent them. For example: R "Newlines is indicated by \ n" # # \ n is not escaped during the reference printing process using the 1.5 Unicode string Unicode is the standard way to write international text. If you want to output a string in a different language, you need to prefix the string with either U or U, for example: U "This is a Unicode string" 1.6 strings connected directly bar two strings together, you can add a comma output space in the middle of the string "the first String "," the second strting "1.7 basic arithmetic * * power, return x y power x**y//divisible 4//3.0 result is 1% modulo << left shift 3<<2 result 12>> right shift 11>>1 results for 5 # # 1011 > 101 It is recommended to use parentheses to complete the connection of operators of different precedence. ~ Bitwise FLIP X's Bitwise rollover yes-(x+1)
Second, the expression, the flow control in any programming process control is not very few, the common flow control has if-else, while, the FOR statement 2.1 if-else statement format: If true:codeelif True:codeelse:done
#!/usr/bin/pythonstr1 = 1if str1 = = 2:p rint "It is true" Else:print "it is false"
The IF statement needs to be appended with a colon at the end of the logical line, indicating that it is followed by a block of statements to be executed, that elif and else are optional, and that if you choose to also add a colon at the end of the logical line, the following is followed by a block of statements to be executed. Note If, elif, else statements are followed by a colon and the code is indented 2.2 while statement format run = truewhile run:if Coderun = Falseelse:codeprint "While loop was done"
#!/usr/bin/python# filname:while.pynum = 1 while num <= 5:print ' number is: ', numif num = 3:print ' num is equal 3 ' E Lse:print "num is not equal 3" num = num + 1print "The while loop was done"
The while statement has an optional else statement and executes if there is an else statement that evaluates to False. If there is an else, it will be executed unless the while loop has been executed. The break statement allows you to exit the loop directly without having to execute the ELSE statement. 2.3 For loop format: For I in range () using the built-in range function to generate sequences such as range (0,6) generate sequence 0-6 You can also use the enumeration sequence [0,1,2,4]. If it is contiguous, then the range (m,n) range (M,N,Q) represents each step from m to n Q
#!/usr/bin/python#filename:for.pyfor i in range (0,6): print IFOR J in [0,1,2,4]: print jfor m in range (0,7,2):
print m
2.4 Break statements and continue statements are consistent with other programming languages, break exits the loop directly, continue completes the loop, and continues the next loop. Functions function 3.1 definition function: Keyword def def func (): #when define a function in Python, there are a comma after function Namecode func () #call the function, which can be used to define parameters in parentheses, for subsequent pass arguments.
#!/usr/bin/python# Filename:func_local.pydef func (y): global x print ' x is: ', x x = 2 print ' Changed lo Cal X to ', xx = 50del funcfunc (x) print ' x is still ', XPrint DIR ()
Q1: Is the value or the address of the parameter passed to the formal parameter during a function call? a1:3.2 variables defined within a local variable function are not related to external variables of the same name, and all variables are scoped to the code block in which they reside
#!/usr/bin/python# Filename:func_local.pydef func (x):p rint ' x is ', xx = 2print ' Changed local x to ', XX = 50func (x) print ' X is still ', X
Execution result for x is 50Changed local x to 2
X is still 50 3.3 global variables use the global definition to specify multiple global variables using the same global statement. For example, Global x, Y, Z. 3.4 The default parameter value parameter is specified internally in the parentheses of the function definition, separated by commas. However, when a function defines a default parameter value, the default parameter value is used when the function is called, and the parameter with the default value must be declared later, such as Def func (x,y=5) but cannot declare def func (X=5,y). The parameter is passed as a position, and when Y is not a value during the call, an error is made.
#!/usr/bin/pythondef func (x,y=5) area = x * yprint ' area is: ', Areafunc (2) func (3,8)
Then the func (3) output is 15func (3,8) output is 24 3.5 key parameter If a function has many parameters, you can use the name of the parameter to specify the value of the corresponding argument in the process of calling the parameter, so that the order of the parameters is not considered, and the assignment rules for the default parameter values are followed. The invocation logic is relatively clear. Such as:
#!/urs/bin/python#filename:func_key.pydef func (a,b=5,c=10) print ' A is ', A, ' B is ', B, ' C is ', C func (3,7) func ( a=10,b=109) func (c=100,a=12,b=23)
The 3.6 Return statement returns a value after the function execution completes, and if there is no return statement, each function implicitly implies a return none statement, none representing a special type that does not have any value in Python. It should resemble the Nullpass statement in Python that represents an empty statement 3.7 docstringsdocstrtings is called a document string, and is an important tool as a description document for the program. The format is as follows: The string in the first logical line of the function is the document string for the function, the same applies to modules and classes, and the Convention of a document string is a multiline string ("'" "or" "" "" ") whose first line begins with an uppercase letter, ending with a period. The second line is a blank line, and the third line starts with a detailed description. This convention is followed when using a document string in a function. Help (Func_name) in the function calls the function's __doc__ (double underscore). #!/usr/bin/python
# Filename:func_doc.py
def printmax (x, y):
"' Prints the maximum of the numbers.
The values must be integers. "
x = Int (x) # Convert to integers, if possible
y = Int (y)
If x > Y:
Print x, ' is maximum '
Else
Print Y, ' is maximum '
Printmax (3, 5)
Print Printmax.__doc__help (printmax.__doc__, Module 4.1 Module Introduction module is a file that contains all the variables and functions that you have customized, ending with a. py. Each of the. py files, called a module,module, can be imported as a library function, and the variables defined in the module can be used in other modules after import. Called with the English dot number, the module is the Pyhon highest-level program organizational unit that encapsulates program code and data for reuse. In practical terms, modules often correspond to Python program files.
Each file is a module, and the module can use the variable name defined by the import module after it has been imported into another module. The module can be processed by two statements and an important built-in function.
Import: Causes the Client (importer) to obtain a module as a whole. # # #导入模块时, without the suffix of the module, such as. py, to determine the rules under import. Import is placed in front of the program and is sorted from top to bottom in the order of the Python standard library module, the Python third-party module, and the custom module. From: Allows the client to obtain a specific variable name from a module file. The specified property #从sys模块中导入argv相关参数 in the From SYS import argv import module, which can be invoked using the parameter name in the script using the From XX import xx, without having to precede the module name with a dot to invoke, But generally to avoid this situation, easy variable conflict. Module import features: from sys import * #导入sys模块中所有的参数, Reload: Provides a way to reload the module file code without aborting the Python program 4.2. PYc file A more detailed introduction to Python. PYc File blog, Blogger also has other Python related blogs, can refer to the following: Http://blog.163.com/[email PROTECTED]/BLOG/STATIC/52600902200812862955306/PYC After the py file has been compiled binaries, the py file becomes a PYc file, the speed of loading the module in other Python scripts is increased, and PYC is a cross-platform bytecode that is executed by Python's virtual machine. PYC content, is related to Python version, the different version of the compiled PYc file is different, 2.5 compiled PYC files, 2.4 version of Python is not executable. PYC files can also be deserialized, and different versions of the compiled PYC files are different. How to compile the py script into a pyc file, as follows:
With the built-in module Py_compile compile, after the completion of the file directory to generate the same name of the. pyc file, Linux under the file name can see Files properties for Python compiled files
>>>import Py_compile
>>>py_compile.compile ("file")
4.3 dir () function
Use the Dir () function to list the names of identifiers defined in the module, identifiers have functions, variables, and classes
such as DIR (SYS) lists the identifier names in the Sys module. null function without Parameters Dir () lists the identifier name of the current module. For example, use Print dir () in the module to print out identifiers in the module.
4.4 List
Use del in Python to delete variables/names/functions.
List list_test = [' Apple ', ' mango ', ' carrot ']
List_test.append (' rice ') adds a value to the list
List_test.sort () sort the list
Len (list_test) Gets the list length del list_test[0] Delete list The first item 4.5 tuples Tuples and lists are very similar, tuples are immutable and cannot be modified. Tuples are defined by comma-delimited items in parentheses tuple_test = (' Wolf ', ' Elephant ', ' monkey ') new_tuple_test = (' Penguin ', tuple_test) print Tuple_test[0] # wolfprint new_tuple_test[1][2] #monkey access by index 4.6 print syntax #!/ Usr/bin/pythonage = 15name = ' python ' # When single quote mark is need during create variables???? Print '%s is a good programming language, it had%d years '% (name,age) print '%s is a good programming language '%nam E #NOTICE: No comma before%nameprint '%s is a good programming language '% (name) 4.7 Dictionary dictionary is di There are two concepts in the instance/object Dictionary of the CT class: Key, Value. You must use an immutable object (string) as the key for the dictionary, the value of the dictionary does not require a key-value pair: dic = {' key1 ': ' value1 ', ' key2 ': ' value2 ', ' Key3 ': ' Value3 '} key-value pairs are separated by colons, and each team is separated by commas, All key-value pairs are placed in curly braces, and key-value pairs are unordered. You need to use single quotation marks.
#!/usr/bin/python#filename:using_dict.py#b = {Key1:value1,key2:value2} #abc = {' Key3 ': ' Value3 ', ' key4 ': ' Value4 '} #print "Key1 ' s value is%s"%ab[key1] #print "Key3 ' s value is%s"%abc[' Key3 '] ab = {' Swaroop ': ' [email protected] ', ' Larry ': ' [email protected] ', ' Matsumoto ': ' [email protected] ', ' Spammer ': ' [email protected] '}print ' Swaroop's address is%s "%ab[" Swaroop "]ab[" Guido "] =" [Email protecte D] "del ab[" spammer "]print" \nthere is%d contacts in the address-book\n "%len (AB) <strong>for name,address in Ab.ite MS (): #调用了键值对的items方法, returns a key-value pair of 2 tuples (keys and values) </strong>
<strong style= "FONT-SIZE:14.4PX; Font-family:arial, Helvetica, Sans-serif; ><span style= "White-space:pre" ></span><span></span></strong><pre name= "code" class= "python" style= "FONT-SIZE:14.4PX; Display:inline!important; " >print "contact%s at%s"% (name,address) <span style= "White-space:pre" ></span>
<span></span><pre name= "code" class= "Python" style= "FONT-SIZE:14.4PX; Display:inline!important; " ><span style= "FONT-SIZE:14.4PX; Font-family:arial, Helvetica, Sans-serif; > #分别赋值给name和address <span></span></span>
If "Guido" in AB: print "\nguido ' s addressis%s"%ab["Guido"]
4.8 sequence lists, tuples, and strings are sequences, primarily specific: index operators and slice operators. 4.9 References note different results in two ways
#!/usr/bin/python#filename:reference.pyshoplist = ["Apple", "Mango", "carrot", "banana"]mylist = Shoplistprint " Shoplist is: ", Shoplistprint" MyList are: ", mylist#shoplist is: [' apple ', ' mango ', ' carrot ', ' banana ') #mylist is: [' Apple ', ' mango ', ' carrot ', ' banana ']del shoplist[0]print "shoplist is:", Shoplistprint "MyList are:", mylist#shoplist is: [' Man Go ', ' carrot ', ' banana '] #mylist is: [' mango ', ' carrot ', ' banana ']print ' copy by making a full slice ' mylist = shoplist[:]d El Mylist[0]print "Shoplist is:", Shoplistprint "MyList is:", mylist#shoplist are: [' mango ', ' carrot ', ' banana '] #mylist is : [' carrot ', ' banana ']
Fifth Python project (backup file) Chapter sixth object-oriented programming seventh, input/output the commonly used input/output type is processing files. The ability to create, read, and write files is required by many programs.create a file from the object of the file class, use the Read,readline and write methods of the file class to read and write the files, and close the file using the Close method to end the operation.
#!/usr/bin/python#Filename:using_file.pyPoem="""Programming is funwhhen the work are doneif you wanna make your work also fun:use python!"""F= File ("Poem.txt","W") f.write (poem) F.close () F= File ("Poem.txt") whileTrue:line=F.readline ()ifLen (line) = =0: Break Printline,f.close ()
View Code
Python Learning Notes