Python automated O & M course-Day2, python automation-day2

Source: Internet
Author: User

Python automated O & M course-Day2, python automation-day2

This article summarizes the content learned from the second day of the Python automated O & M course for old boys.

The general content is as follows:

1. First knowledge of the python Module

2. python program running process

3. python data types (only numbers, bool, strings, bytes, list, tuple, dict, set)

4. python Data Operations

0. For all the environments running Python code in this article:

-- Operating System: Ubuntu 16.10 (Linux 4.8.0)

      

-- Python version: 3.5.2

      

-- Python IDE: PyCharm 2016.3.2

      

1. Familiar with the Python module. The Python module consists of a standard library and a third-party Library:  

1) standard library (build-in lib)The module (Library) that comes with python installation is generally stored in the lib folder in the installation path:

Windows: C: \ Users \ [username] \ AppData \ Local \ Programs \ Python \ Python35 \ Lib \

Linux:/usr/lib/python3.5/

    2) third-party libraries:After installing python, you need to install another module (Library), which is generally stored in the site_packages folder in the installation path:

Windows: C: \ Users \ [username] \ AppData \ Local \ Programs \ Python \ Python35 \ Lib \ site_packages \

Linux:/usr/lib/python3.5/site_packages/

To reference the functions in these modules, you must passImportYou can use each function in the module only after importing the module to be referenced.

In this lesson, we will simply learn about the two standard modules sys and OS.

1) sys module: Provides interfaces for the python interpreter to interact with users. Such as sys. exit () and sys. path.

    Official explanation: This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available. For details, see examples.

Sys. path: Print Python Global Environment Variables

Sys. arve: If the python program is executed without any parameters (separated by spaces), print the path of the python code file;

If a parameter exists, all parameters are printed (in the form of lists );

If sys. arve [N]: prints the nth parameter. If N is greater than the total number of subsequent parameters, the error "out of range" is returned.

#! /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's global environment variable information print ("sys. path ", sys. path) # print the Python program file path (absolute path in Windows and relative path in Linux) print ("\ nsys. argv ", sys. argv) # print the 1st parameters that follow the execution of the Python program file 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 interfaces for the interaction between the python interpreter and the operating system. Such as OS. path and OS. error.

    Official explanation: This module provides a portable way of using operating system dependent functionality. For details, see https://docs.python.org/3.5/library/ OS .html#module-os.

OS. system (""): Call system commands, such as OS. system ("ls-lh") and OS. system ("dir.

OS. mkdir (""): Call the mkdir command of the system to create a 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 the system command ls-lh to display the print (OS. system ("ls-lh") bytes _line = OS. system ("ls-lh") # If the command is successfully executed, 1 is returned; otherwise, 0 print ("\ n1__line:", 1__line) # create the OS folder test_day2. mkdir ("test_day2") # Use popen () to replace system () using _result = OS. popen ("ls-lh") # print the Address in the memory print ("\ n1__result Address in memory:", 1__result) # read () print the export _result value print ("\ n export _result:", export _result.read () # create the test_day2 folder and report the OS error. mkdir ("test_day2") # End Of File

    

 

2. Python program running process  

Python is an interpreted language and involves two concepts during execution: PyCodeObject and pyc files.

     PyCodeObject:Indicates the object in memory that stores the results of Python code execution.

Pyc file:A Python code execution result stored on a disk. It can be regarded as a persistent storage of PyCodeObject. Therefore, after executing the python code, we will see a. pyc file with the same name as the python code file (. py) in the same path as the python code file.

    

 

3. Python data types (numbers, bool, strings, bytes, list, tuple, dictionary, set)

Numbers:Int, long, fload, complex (plural)

Bool:True (number 1), False (DATA 0): In Python2, there is no boolean type. It uses the number 0 to indicate False, and 1 to indicate True. In Python3, True and False are defined as keywords, but their values are still 1 and 0. They can be computed with numbers.

    Strings:String, single or double quotation marks, or triple quotation marks. String concatenation: when modifying the string content, you need to open up the memory space again. The same is true for concatenating strings through "+.

    Bytes:A Bytes object is a sequence composed of a single byte as the basic element (8-bit, value range: 0-255). It is an immutable object. The Bytes object is only responsible for recording the objects to be recorded in the form of a binary byte sequence. The decoding of the object's actual representation (for example, what character) is determined by the corresponding encoding format. (Reference https://segmentfault.com/a/1190000004450876)

#! /Usr/bin/python3.5 #-*-coding: UTF-8-*-# Function: check the bytes # Author: Spencer Jiang # Date: 2017-02-18str_name = "string" print ("name -- UTF-8:", bytes (str_name, "UTF-8") print ("name -- gb2312:", bytes (str_name, "gb2312 "))

    

List ):

1) An ordered set of elements, starting from and ending with square brackets. Each element is separated by commas (,), for example, list_a = [1, 2, 3, 4, "test"].

2) The starting subscript of the List is 0.

3) operations supported by the list:

        A. Query: List_a [I], list_a.index ("test"), and 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) # print (list_a [4]) print (list_a [-1]) # print (list_a.index ("test") of an element # print (list_a.count (4) of an element ))

      

B. Slice: Take all the elements in a certain range, list_a [I: j: len], I is the starting subscript, and the default value is 0; j is the ending subscript, and the default value is the length of list_a-1; len is the step size. The default value is 1.

    

        C. Update:

Add a new element at the end of the list: list. append (value );

Insert an element at the specified position in the list: list. insert (I, value );

Modify the value of the element corresponding to the specified Subscript: list [I] = value;

Sort the Data Types of all elements in the list by ASCII code: list. sort (); if the list element contains both numbers and strings, the sort () function reports the error "TypeError: unorderable types: str () <int ()".

Reverse all elements in the list: list. reverse ();

Splicing of different lists: list_a.extend (list_ B) connects all elements in list_ B to the end of 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 list_a.append ("hello") to the end of the list ") print ("list_a.append ('hello'):", list_a) # insert an element list_a.insert (2, 123123) print ("list_a.insert (2, 123123 ):", list_a) # modify the value of the element corresponding to the specified subscript list_a [1] = "B" print ("list_a [1]:", list_a) # sort all elements by ASCII code # list_a.sort () # If the elements in the list have both numbers and strings, the sort () function reports the error "TypeError: unorderable types: str () <int () "list_ B = [123, 3, 54,234, 23, 4] list_ B .sort () print (" list_ B .sort (): ", list_ B) # reverse all elements in the list to list_ B .reverse () print ("list_ B .reverse ():", list_ B) # connect all elements in 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 ()

Delete the specified Element in the list: list_a.remove (value)

Delete the element specified in the list: list_a.pop (I)

Delete the target element in the list: del list_a [I]

Clear all elements in the list: list_a.clear ()

Delete the 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 () 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 specified in the list: list_a.pop (I) list_a.pop (1) print (" list_a.pop (1): ", list_a) # Delete the element specified in the list: del list_a [I] del list_a [1] print ("del list_a [1]:", list_a) # clear all the elements in the list: list_a.clear () print ("list_a.clear ():", list_a) # Delete the entire list: del list_adel list_aprint (list_a) # The list_a object is deleted, print error "name'list _ a' is not defined"

      

E. copy operation: Copy

Directly assign a list value to another list: list_ B = list_a. All elements in list_ B and list_a are consistent in real time.

Shallow copy: list_a = list_ B .copy () or by importing the copy package, list_a = copy. copy (list_ B), only the elements in the nested list will be consistent in real time.

Deep copy: by importing the copy package, list_a = copy. deepcopy (list_ B), no matter whether it is a nested list or not, all elements are consistent in real time.

 

Tuple (tuples ):Tuples are immutable lists with parentheses as the start and end tags. Each element is separated by commas (,), for example, tuple_a = (1, 2, 3, "test "), the starting subscript is 0.

Operations supported by tuples: Take the element value tuple_a [I] of a certain base object, obtain the subscript tuple_a.index ("test") corresponding to an element, and count tuple_a.count (1) of an element ).

#! /Usr/bin/python3.5 #-*-coding: UTF-8-*-# Function: check tuple # Author: Spencer Jiang # Date: # The list of tuples is immutable, starts and ends with parentheses. Each element is separated by commas (,) name_tuple = (1, 2, 3, "wu", "test", "SZ", "wu ") print (name_tuple) # Start subscript is 0 print (name_tuple [1]) # print (name_tuple.count ("wu ")) # print (name_tuple.index ("SZ "))

    

Set ):Unordered, automatically de-duplicated data combinations, 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 the result

       A. Operation:

Take the Union of set_a and set_ B: set_a | set_ B

Take the intersection of set_a and set_ B: set_a & set_ B

Take the difference set of set_a and set_ B: set_a-set_ B

Set the symmetry 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 the Union of set_a and set_ B: set_a | set_bprint (set_a | set_ B) # intersection of set_a and set_ B: set_a & set_bprint (set_a & set_ B) # difference set between set_a and set_ B: set_a-set_bprint (set_a-set_ B) print (set_ B-set_a) # Set of symmetry differences between set_a and set_ B: set_a ^ set_bprint (set_a ^ set_ B)

     

B. New operations:

Add one element: set_a.add (value)

Add multiple elements: set_a.update (value1, value2, value3 ...)

Merge two sets: set_a.union (set_ B), equal to set_a | set_ B

C. Delete:

Randomly remove 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 the 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:

          Obtain all the elements in set_a that do not belong to set_ B: set_a.difference (set_ B)

 

Dictonary (dictionary ):The unordered key-value pair must be unique in the data set. Start and end with braces {}, and separate key and value with a colon.

A. Query: Query the value of a key: dist. get (key), dist [key]

Get all keys: dist. keys ()

Get all values: dist. values ()

Get all key-value: dist. items ()

B. Update:

Update the value of a key: dist [key] = value. If the key is not present, it is added. If the key exists, it is updated.

Set the default value of a key: dist. set (key, value)

Merge two dists: disct. update (dist_ B), merge dist_ B into dist, and overwrite if the key is duplicate

         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": 23,        "job": ["Dev", "Test"]    },    "Jack": {        "sex": "boy",        "age": 17,        "job": "stud"    },    "Jen": {        "sex": "girl",        "age": 22,        "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 is the data type Mind Map:

4. Python data operation and operation Priority

1. Arithmetic Operation:+ (Plus),-(minus), * (multiplication),/(except), % (Modulo), // (the integer part of the operator), ** (power)

In a computer, all arithmetic operations must be converted to binary before calculation.

#!/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)=", a - 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 operators:= (Determine whether two objects are equal ), ! = (Determine whether two objects are not equal),> (greater than), <(less than), <> (not equal, this symbol is not recommended),> = (greater than or equal), <= (less than or equal)

3. Value assignment operator [Add an equal sign (=) after the Arithmetic Operator)]:= (Simple assignment), + = (addition assignment),-= (subtraction assignment), * = (multiplication assignment),/= (Division assignment), % = (Modulo value assignment), // = (operator integer value assignment), ** = (power value assignment)

4. logical operators:Or (or), and (and), and not (not) are used to calculate one or more conditions in a condition 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 it can be found in the specified list; otherwise, False), not in (returns True if it cannot be found in the specified list; otherwise, False)

6. Identity calculation:Is (determine whether two identifiers reference the same object), not is (determine whether the two identifiers do not reference the same object)

7. bitwise operations:& (By bit and), | (by bit or), ^ (by bit or ),~ (Bitwise inversion), <(left shift operation),> (right shift Operation)

    1) bitwise and operation (&):When the binary values of the two numbers are both 1 (true), the value is 1 (true); otherwise, the value is 0 (false ).

Example: a, B = 123,-123

A & B = 0111 1011 & 1000 0101 = 0000 0001 = 1

      Note: The negative number is expressed by a complement in binary.-- Take B =-123 as an example:

A) first take the binary value of its absolute value (calculated in 8-bit binary values. The binary value of 123 is 0111 1011. The first value is 0, indicating a positive number, and the first value is 1, indicating a negative number)

B) Perform bitwise inversion and change to: 1000 0100

C) Add 1 to the last position, which is the completion code: 1000 0101

    2) bitwise OR (| ):If one of the two values is 1 (true), the value is 1 (true). Otherwise, the value is 0 (false ).

A | B = 0111 1011 | 1000 0101 = 1111 1111 =-1

3) bitwise XOR (^ ):When the values of the two numbers are both 1 (true) or 0 (false), the value is 0 (false); otherwise, the value is 1 (true ).

A ^ B = 0111 1011 ^ 1000 0101 = 1111 1110 =-2

    4) bitwise inversion (~) :Perform operations on only the number 1. Take the opposite digit for the values on the binary number. That is, if the value is 0, the value is reversed to 1. If the value is 1, the value is reversed to 0.

(1) Inverse Process of positive numbers :~ A =-124 =-(a + 1)
A. convert a positive number to a binary number (calculated in 8-bit binary), and add a sign at the beginning to 0 to indicate a positive number, and 1 to indicate a negative number:
For example, a = 123; binary number: 0 0111 1011
B. Obtain the complement of the binary number: 0 0111 1011 (the positive complement is itself, and the negative complement is bitwise AND THE LAST complement is 1)
C. bitwise inversion: 1 1000 0100
D. bitwise inversion (the symbol bit remains unchanged): 1 0111 1011
E. If the first digit is 1 (indicating a negative number), add 1 to the last digit. 1 0111 1100 (-124) (2) negative number inversion process :~ B = 122 =-(B + 1)

A. convert a positive number to a binary number, and add a sign at the beginning to 0 to indicate a positive number, and 1 to indicate a negative number:
For example, B =-123; obtains the binary number of the absolute value. The first digit is the symbol bit, which is 1 0111 1011
B. Obtain the complement of the binary number: 0 1000 0101 (the positive complement is itself, and the negative complement is bitwise AND THE LAST complement is 1)
C. bitwise inversion (the symbol bit remains unchanged): 0 0111 1010 (122)

    5) Left shift operation:Only one number of operations. The expression is A <X, indicating that all binary bits of A are shifted to the left, and 0 is added to the right.

6) right shift operation:Only one number of operations. The expression is A> X, indicating that all binary bits of A are shifted to the right.

#!/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  1000 0101" % b)print("b<<2 = ", b << 2)print("a>>2 = ", a >> 2)

    

8, Three-element operation:Operations on three 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. Everything in Python is an object.

 

Assignments for week 2 ------ shopping cart

1. User portal and merchant portal
2. User Portal:
1) deposit (salary) is required only when the program is run for the first time)
2) Read product information from the file
3) after purchasing the product, the list of purchased products and the account balance are displayed and saved to the file.
3. merchant portal:
1) You can add or modify the product price.
2) store product information in a file

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.