This article summarizes the next day's study of the old boy's Python automated operations course.
The general contents are as follows:
1, Python module first knowledge
2. Python program running Process
3. Python data type (only numbers, bool, strings, Bytes, list, tuple, dict, set)
4. Python Data operation
0. For all the environments in this article that run Python code:
--Operating system: Ubuntu 16.10 (Linux 4.8.0)
--python version: 3.5.2
--python Ide:pycharm 2016.3.2
1, Python module, Python module is divided into standard libraries and third-party libraries:
1) Standard library (build-in Lib) is a module (library) that is installed after Python and is typically stored under the Lib folder under the installation path:
Windows:c:\users\[username]\appdata\local\programs\python\python35\lib\
Linux:/usr/lib/python3.5/
2) Third-party libraries: after the installation of Python, additional modules (libraries) are required, typically stored under the installation path under the Site_packages folder:
Windows:c:\users\[username]\appdata\local\programs\python\python35\lib\site_packages\
Linux:/usr/lib/python3.5/site_packages/
To reference the functionality in these modules, you must import the modules to be referenced by importing at the beginning of the Python code before you can use each feature in the module.
This lesson is simple to understand the next SYS and OS two standard modules.
1) SYS module: Provides interface functions for the Python interpreter to interact with the user. such as Sys.exit (), Sys.path and so on.
Official explanation: This module provides access to some variables used or maintained by the interpreter and to functions that interact St Rongly with the interpreter. It's always available. See Https://docs.python.org/3.5/library/sys.html#module-sys.
sys.path: Print python Global environment variables
Sys.arve: If the Python program is executed, the path of the Python code file is printed after it is not followed by any parameters (separated by a space between the parameters);
If there are parameters, all parameters are printed (printed in lists);
If Sys.arve[n]: Prints the nth parameter that follows. If n is greater than the total number of subsequent parameters, the "Out of range" error is reported.
#!/usr/bin/python3.5#-*-coding:utf-8-*-# function:check the SYS mode with Sys.path and sys.argv# author:spencer Jiang # date:2017-02-18import sys# Print Python Global environment variable information print ("Sys.path", Sys.path) # Print Python program file path (absolute path under Windows, relative path under Linux) Print ("\nsys.argv", SYS.ARGV) # Prints execute Python program file followed by the 1th parameter print ("\nsys.argv[1]", Sys.argv[1]) # ARGV error: Out of Rangeprint ( "\nsys.argv[1]", sys.argv[10]) # End of File
2) OS module: Provides interface functionality for the Python interpreter to interact with the operating system. such as Os.path,os.error and so on.
Official explanation: This module provides a portable the using operating system dependent functionality. See Https://docs.python.org/3.5/library/os.html#module-os.
Os.system (""): Invoke system commands such as Os.system ("Ls-lh"), Os.system ("dir"), and so on.
Os.mkdir (""): Call the system's mkdir command to create the directory
#!/usr/bin/python3.5#-*-coding:utf-8-*-# function:check the OS mode with Os.open (), Os.system (), Os.popen (), Os.mkdir ( # author:spencer jiang# date:2017-02-18import os# call system command LS-LH Show list of all files and directories under current path print (Os.system ("LS-LH")) Cmd_line = OS . System ("LS-LH") # returns 1 if the command executes successfully, otherwise 0print ("\ncmd_line:", cmd_line) # Create Test_day2 folder Os.mkdir ("Test_day2") # with Popen () Replace system () Cmd_result = Os.popen ("Ls-lh") # Print in memory address print ("\ncmd_result address in Memory:", Cmd_result) # read () print cmd_re Sult value Print ("\ n cmd_result:", Cmd_result.read ()) # Again create Test_day2 folder, Error Os.mkdir ("Test_day2") # End of File
2. Python program running Process
Python is an interpreted language that involves two concepts during execution: Pycodeobject and PYc files
Pycodeobject: refers to the object stored in memory by the result of Python code execution
pyc file: refers to a file that is saved to disk by Python code execution results and can be considered a persistent storage for pycodeobject. So after we execute the Python code, we see a. pyc file with the same name as the Python code file in the Python code file (. py) under the same path.
3. Python data type (numbers, bool, strings, Bytes, list, tuple, dictionary, set)
Numbers: int, long, fload, complex (plural)
Bool: True (number 1), False (data 0): There is no boolean in Python2, it uses the number 0 to indicate False, and 1 for true. In Python3, true and false are defined as keywords, but their values are 1 and 0, and they can be calculated with numbers.
Strings: A string, single or double or triple quotation marks. string concatenation: When modifying the contents of a string, it is necessary to open up the memory space again, and the same is true with the "+" stitching string.
Bytes: A Bytes object is a sequence of a single byte that is a basic element (8 bits, a value range of 0-255), and is an immutable object. The Bytes object is only responsible for recording the desired record in the form of a binary byte sequence, as determined by the corresponding encoding format, as to what exactly the object represents (for example, what character). (Ref. 1190000004450876)
#!/usr/bin/python3.5#-*-coding:utf-8-*-# function:check the bytes# author:spencer jiang# date:2017-02-18str_name = " The string "Print" ("name--utf-8:", Bytes (str_name, "Utf-8")) Print ("name--gb2312:", Bytes (str_name, "gb2312"))
list (lists):
1) An ordered set of elements, with square brackets as the start and end tags, with elements separated by commas, such as List_a = [1, 2, 3, 4, "test"].
2) The starting subscript for the list is 0.
3) List of supported actions:
A, query : Take the element value of a subscript list_a[i], take an element corresponding to the subscript list_a.index ("test"), an element count List_a.count (1).
#!/usr/bin/python3.5#-*-coding:utf-8-*-# function:list query ops# author:spencer jiang# date:2017-02-27list_a = [1, 2, 3, 4, "Test", 4, "abc"]print (list_a) # Take a subscript element value print (List_a[4]) print (list_a[-1]) # take an element corresponding to the subscript print (List_a.index ("Test ") # Count of some elements print (List_a.count (4))
B, Slice : Take all elements within a range list_a[i:j:len],i as the starting subscript, the default is 0;j for the end subscript, the default is list_a length -1;len is the step, the default is 1.
C, update :
Add a new element at the end of the list: List.append (value);
Inserts an element at the specified position in the list: List.insert (i, value);
The value of the corresponding element for the specified subscript is modified: list[i]=value;
Sorts the data types of all the elements in the list in ASCII code: List.sort (); if the elements in the list have both numbers and strings, the sort () function will error "typeerror:unorderable Types:str () < int ()".
Reverses all the elements in the list: List.reverse ();
Splicing of different lists: List_a.extend (list_b), connecting all elements in the list list_b to the end of the list_a.
#!/usr/bin/python3.5#-*-coding:utf-8-*-# function:list query ops# author:spencer jiang# date:2017-02-27list_a = [1, 2, 3, "Test", 4, "abc"]print ("List_a:", list_a) # Add a new element at the end of the list list_a.append ("Hello") print ("List_a.append (' Hello '):", LIST_A) # Inserts an element at the specified position in the list List_a.insert (2, 123123) print ("List_a.insert (2, 123123):", list_a) # Modifies the value of the specified subscript corresponding element list_a[1] = "B" Print ("list_a[1]:", list_a) # Sorts all the elements in ASCII code # List_a.sort () # The elements in the list have both a number and a string, and the sort () function will error "typeerror:unorderable TYPES:STR () < int () "List_b = [123, 3, Si, 234, 23°c, 4]list_b.sort () print (" List_b.sort (): ", List_b) # Reverses all the elements in the list list_b.re Verse () Print ("List_b.reverse ():", List_b) # connects all the elements in the list list_a to the end of List_b list_b.extend (list_a) print ("List_b.extend ( LIST_A): ", List_b)
D, delete :
Delete the last element in the list: List_a.pop ()
Removes the specified element from the list: List_a.remove (value)
Delete the element that specifies the subscript in the list: List_a.pop (i)
Delete the element that specifies the subscript in the list: Del List_a[i]
Empty all the elements in the list: List_a.clear ()
Delete entire list: Del list_a
#!/usr/bin/python3.5#-*-coding:utf-8-*-# function:list query ops# author:spencer jiang# date:2017-02-27list_a = [1, 2, 3, "Test", 4, "abc", "CDE"]print ("List_a:", list_a) # Delete the last element in the list: List_a.pop () List_a.pop () print ("List_a.pop ():", list_a) # Delete the specified element in the list: List_a.remove (value) list_a.remove ("abc") Print ("List_a.remove (' abc '):", List_a) # Delete the element that specifies the subscript in the list: List_a.pop (i) list_a.pop (1) Print ("List_a.pop (1):", list_a) # Delete the element in the list that specifies the subscript: del List_a[i]del list_a[1] Print ("Del list_a[1]:", list_a) # Clears all the elements in the list: List_a.clear () list_a.clear () print ("List_a.clear ():", list_a) # to delete the entire list: Del List_adel list_aprint (list_a) # List_a object is deleted, printing error "name ' list_a ' is not defined"
E, copy operation : Copy
Assign a list directly to another list: List_b = all elements in List_a,list_b and list_a are consistent in real time.
Shallow copy:list_a = List_b.copy () or by importing a copy package, list_a = Copy.copy (List_b), only the elements in the nested list will be in real-time consistency.
Deep copy: By importing a copy package, list_a = Copy.deepcopy (list_b), regardless of the nested list, all elements are in real-time consistency.
tuple (tuple): tuples are immutable lists, with parentheses as the start and end tags, and elements separated by commas, such as Tuple_a = (1, 2, 3, "test"), starting with the subscript 0.
Tuple-supported operations: Take a subscript element value tuple_a[i], take an element corresponding to the subscript tuple_a.index ("test"), count an element Tuple_a.count (1).
#!/usr/bin/python3.5#-*-coding:utf-8-*-# function:check tuple# author:spencer jiang# date:2017-02-27# tuples are immutable lists, in parentheses Start and end tags, elements separated by commas name_tuple = (1, 2, 3, "WU", "Test", "SZ", "WU") print (name_tuple) # start subscript 0print (name_tuple[1]) # Count print for an element (Name_tuple.count ("WU")) # takes an element corresponding to the subscript print (Name_tuple.index ("SZ"))
Set (SET): unordered, auto-deduplication data combination, defined by the set () function, set_a = set ("Hello, Python").
Set_a = set ("Hello, Python") print (SET_A)
{' Y ', ', ' h ', ' e ', ', ', ' l ', ' t ', ' n ', ' P ', ' O '} # Print Results
A, Operation operations :
Take the Set_a and Set_b: set_a | Set_b
Take the intersection of Set_a and Set_b: Set_a & Set_b
The difference between set_a and Set_b: Set_a-set_b
Symmetric difference between set_a and set_b: set_a ^ set_b
Set_a = set ("Hello, Python") print (set_a) Set_b = set ("Hello, World") print (set_b) # take set_a and Set_b's set: Set_a | Set_bprint (Set_a | set_b) # take Set_a and Set_b intersection: Set_a & Set_bprint (Set_a & Set_b) # take set_a and Set_b difference set: set_a-set_ Bprint (set_a-set_b) print (set_b-set_a) # take set_a and set_b symmetrical difference set: set_a ^ set_bprint (set_a ^ set_b)
B, new operation :
1 new elements added: Set_a.add (value)
Added multiple elements: set_a.update (value1, value2, value3 ...)
Merge two collections: Set_a.union (Set_b), Equals Set_a | Set_b
C, delete :
Random removal of an element: Set_a.pop ()
Remove an element: Set_a.remove (value)
Set_a = set ("Hello, Python") print (set_a) set_a.add ("1") Set_a.update ("2", "3") print (set_a) set_a.remove ("H") print (set _a) Print (Set_a.union (Set ("HELLO"))) Set_a.pop () print (set_a) # # Run result {' O ', ' e ', ' l ', ' t ', ' n ', ', ', ' P ', ' Y ', ' H ', '} {' O ', ' E ', ' l ', ' t ', ' 2 ', ' n ', ', ', ' P ', ' Y ', ' h ', ' 3 ', ' ', ' 1 '} {' O ', ' e ', ' l ', ' t ', ' 2 ', ' n ', ', ', ' P ', ' Y ', ' 3 ', ', ' 1 '} {' O ' , ' l ', ' e ', ' H ', ' e ', ' l ', ' t ', ' 2 ', ' n ', ' O ', ', ', ' P ', ' Y ', ', ' 3 ', ' 1 '} {' E ', ' L ', ' t ', ' 2 ', ' n ', ', ', ' P ', ' Y ', ' 3 ', ', ' 1 '}
D, Comparison operation:
Get all elements in set_a that are not part of Set_b: Set_a.difference (Set_b)
dictonary (dictionary): unordered key-value to data collection, key must be unique. Begins and ends with curly braces {}, separated by a colon before key and value.
A, Query : Query the value corresponding to a key: Dist.get (Key), Dist[key]
Get all Key:dist.keys ()
Get all Value:dist.values ()
Get all Key-value:dist.items ()
B, update :
Update the value of a key: Dist[key] = value, if key is not present, new;
Set the default value for a key: Dist.set (key, value)
Merge two dist:disct.update (dist_b), merge dist_b into Dist, and overwrite if key is repeated
C, delete : delete a specified Key-value:dist.pop (key)
Randomly delete an element: Dist.popitem ()
Delete a specified Key-value:del dist (key)
Dis_person = { "Spencer": { "sex": "Boy", "Age": at $, " Job": ["Dev", "Test"] }, "Jack": { " Sex ":" Boy "," Age ": +," job ":" Stud " }, " Jen ": { " sex ":" Girl ", " age ":" Job ":" Stud " }}print (dis_person[" Spencer "]) print (dis_person[" Spencer "[" Job "]) print (Type (Dis_person.keys ()), Dis_ Person.keys ()) Print (Dis_person.get ("Jen")) print (Type (Dis_person.items ()), Dis_person.items ()) Print (Dis_ Person.values ()) dis_person["Spencer"].pop ("Job") Print (dis_person["Spencer"])
Attached to the data type Mind map:
4. Python data operation and operation Priority
1. Arithmetic operations: + (plus),-(minus), * (multiply),/(except),% (modulo),//(integer part of the quotient), * * (Power)
in the computer, all the arithmetic runs must be converted to binary before the operation.
#!/usr/bin/python3.5#-*-coding:utf-8-*-# Function:practice of the calculator# author:spencer Jiang# date:2017-02-22a = 123b = -321print ("123 + ( -321) =", A + B) print ("123-( -321) =",-B) Print ("123 * ( -321) =", A * b) print ("(-321)/123 =" , b/a) print ("123% ( -321) =", a% b) print ("( -321)//123=", b//a) print ("123 * * 2=", a**2)
2, comparison operator: = = (To determine whether two objects are equal ),! = (To determine whether two objects are not equal), > (greater than), < (less than), <> (not equal, not recommended), >= (greater than or equal), <= (less than or equal)
3. Assignment operators [ Add an equal sign (=)] to the arithmetic operator:= (simple Assignment), + = (addition Assignment),-= (subtraction Assignment), *= (multiplication Assignment),/= (division Assignment),%= (modulo assignment),//= (integer assignment of the quotient), **= (Power Assignment)
4. Logical operators:or (or), and (and), not (non), for the operation of single or multiple conditions in a conditional judgment statement.
#!/usr/bin/python3.5#-*-coding:utf-8-*-# function:user login input# author:spencer jiang# date:2017-02-25user_name = Input ("Please input username:") password = input ("Please input password:") _username = "Spencer" _password = "1234ABCD" if User_name = = _username and Password = = _password: print ("Welcome, login successfully!!") Elif user_name! = _username or password! = _password: print ("Invalid username or password!!") else: print ("I am not happy!")
5, member Operation:in (returns True if found in the specified list, false otherwise), not in (returns true if not found in the specified list, false otherwise)
6, identity operation:is (to determine whether two identities refer to the same object), not is (to determine whether two identities do not reference the same object)
7. Bitwise arithmetic:& (Bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise negation), << (left shift operation), >> (right shift operation)
1) Bitwise AND operation (&): Two digits of the binary numbers are 1 (true), 1 (true), otherwise 0 (false).
Example: A, B = 123, 123
A & B = 0111 1011 & 1000 0101 = 0000 0001 = 1
Note: Negative numbers are represented in the binary by complement--take b=-123 as an example:
A) First take its absolute value of binary values (according to 8-bit binary to calculate, 123 of the binary is 0111 1011, the first plus 0 for positive, first plus 1 for negative numbers)
b) re-bitwise reversed, changed to: 1000 0100
c) The bottom plus 1, is the complement: 1000 0101
2) Bitwise OR Operation (|): Two digits of the binary number if there is a value of 1 (true), it is 1 (true); otherwise 0 (false).
A | b = 0111 1011 | 1000 0101 = 1111 1111 = 1
3) Bitwise XOR (^): Two numbers of binary values are both 1 (true), or 0 (false) at the same time, 0 (false), otherwise 1 (true).
a ^ b = 0111 1011 ^ 1000 0101 = 1111 1110 =-2
4) Bitwise reverse (~): only 1 numbers to operate , to the binary number of the values of the opposite one, the even if is 0, then the inverse becomes 1; if 1, the inverse is 0.
(1) inverse process for positive numbers: ~a = -124 =-(a+1)
A, convert positive numbers to binary number (in 8-bit binary), and at the front plus a symbol of 0 for positive numbers, 1 for negative numbers:
such as a = 123; The binary number is: 0 0111 1011
b, take the complement of the binary number: 0 0111 1011 (positive complement for itself, the complement of negative numbers for the bitwise negation plus 1)
C, in the bitwise reverse: 1 1000 0100
D, re-bitwise reversed (sign bit unchanged): 1 0111 1011
E, if the first is 1 (indicating negative numbers), the bottom need to add 1. 1 0111 1100 (-124)
(2) Negative negation process: ~b = 122 =-(b+1)
A, convert positive numbers to binary numbers, and precede with a symbol of 0 for positive numbers and 1 for negative numbers:
such as b=-123; The binary number of its absolute value, preceded by the symbol bit, is: 1 0111 1011
b, take the complement of the binary number: 0 1000 0101 (positive complement for itself, the complement of negative numbers for the bitwise negation plus 1)
C, re-bitwise reversed (sign bit unchanged): 0 0111 1010 (122)
5) Left shift operation: For 1-number operations, the expression is: A<<x, which indicates that the binary of a is shifted to the left by X-bit, and 0to the right.
6) Right shift operation: For operations of only 1 numbers, the expression is: A>>x, which represents the binary all bits of a to the right of the X-bit .
#!/usr/bin/python3.5#-*-coding:utf-8-*-# function:bitwise operations# author:spencer Jiang# date:2017-02-25a = 123b = -123print ("Binary of%d is 0011 1101"% a) print ("Binary of%d is 0101"% b) print ("b<<2 =", b << ; 2) print ("A>>2 =", a >> 2)
8, ternary operation: the operation of 3 operands
#!/usr/bin/python3.5#-*-coding:utf-8-*-# function:three opts# author:spencer jiang# date:2017-02-25b, C = 5, 19a = C If B > C else cprint (a)
Finally: Python is an object-oriented programming language, and everything is object in Python.
The second week of homework------shopping cart
1, divided into user portal and business entrance
2. User Portal:
1), first run the program only need to enter the deposit (salary)
2), read the product information from the file
3), after the purchase of goods, display the list of purchased goods, account balance, and are saved to the file
3. Business entrance:
1), can add goods, modify commodity prices
2), the product information is kept in the document
Python automated operation and maintenance course learning--day2