Summary of basic Python tutorials (1) and summary of basic python tutorials

Source: Internet
Author: User

Summary of basic Python tutorials (1) and summary of basic python tutorials
Introduction:

I have always heard that Python is very powerful. I used to browse some blogs and found that it is a bit like Matlab used in mathematical modeling, so I didn't know much about it. Today, Python is used more and more places, and recently it is learning machine learning. Therefore, I want to learn it systematically, so I feel more at ease. The following is my summary using my own way of thinking when I read "Python basic tutorial version 2". I will talk to myself and link up my knowledge. If I want to use Python again, I will read less information.

 

1. Be aware

Before learning a language, I want to know what it can do. If what it does is the same as what I already know, I may be more interested in learning the syntax. Let's take a look at Baidu encyclopedia's explanation of Python.

Python is an object-oriented, interpreted computer programming language, invented by Guido van rosum at the end of 1989, the first public release was released on August 1, 1991. The Python syntax is concise and clear, and has rich and powerful class libraries. It is often called the glue language. It can easily connect various modules (especially C/C ++) made in other languages. A common application scenario is to use Python to quickly generate a prototype of a program (sometimes even the final interface of the Program) and then have a special requirement on it, rewrite with a more appropriate language. For example, if the graphic rendering module in 3D games has high performance requirements, you can rewrite it with C ++.

It can be seen that it is an interpreted scripting language, so it is similar to Shell. Secondly, it has a powerful class library. "Class Library", I am only familiar with Java. When I hear the class library think of object-oriented, another kind of understanding of the class library is that we can save a lot of coding work, mature class libraries are used to solve some of the functions implemented step by step when writing C or assembly. Again, its nickname is "glue language ". The "glue language" is so powerful that I think of the scenario of writing Java in JSP files, or when Java calls the Native library, it may not be very accurate, it should be more appropriate than the Shell scripting language. Therefore, it has a huge capacity of "inclusiveness" and is very broad-minded. Finally, use Python to quickly generate a program prototype. Wow, isn't that the best way to verify the algorithm. At the earliest, I only had the C language. It was quite difficult to write algorithm programs. In terms of syntax, I had to consider how to implement this algorithm. I don't know what convenience Python can bring to me.

 

2. Chapter 1-Basic Knowledge 2.1. Download and install

Reading this book is the use of Python2.5, to the Python official website under the http://www.python.org Downloads All Releases find the next one.

  

2.2. Numbers and expressions
  • For x = 1/2, 0 is obtained in the C language. To get 0.5, a floating point number is required for calculation, that is, x = 1.0/2. The same applies to Python, but if you want Python to execute normal division without floating point numbers, you need to import them into the database.
>>> from __future__ import division

 

But what should I do when I want to perform Division operations? // (Double slash) x = 1 // 2. Even if a floating point is involved in the operation, that is, x = 1.0 // 2.0, the result is 0.0;

  • Power Operation: x = 2 ** 3. The result is 8. The power operation has a higher priority than the inverse operation. Therefore, x =-3 ** 2 returns-9 and x = (-3) ** 2 returns 9. Or x = pow (-3, 2 );
  • Hexadecimal: 0xAF, which is the same as the C language. It is preceded by 0x;
  • Gossip: 010, same as the C language, the front is 0;
  • Rounded to the nearest integer: round ();
  • Round down: math. floor (32.9). The result is 32.0;
  • Plural operation: cmath. sqrt (-1), result 1j;
Operation Result
X | y BitwiseOrOfXAndY
X ^ y BitwiseExclusive orOfXAndY
X & y BitwiseAndOfXAndY
X <n XShifted leftNBits
X> n XShifted rightNBits
~ X The bitsXInverted

  

 

 

 

 

This operation is similar to the C language.

2.3. String
  • Str (), repr (), and reverse quotation marks ~ Which key is used to convert Python values to strings. The str () function makes the string easier to read, while repr () and reverse quotation marks convert the result string into a valid Python expression.
  • Input () assumes that the user inputs a valid Python expression. raw_input () regards the input as the original data. Raw_input () should be used as much as possible ();
  • Long String, with line breaks, can be written in three quotes "Hello Python """;
  • You can use the backslash (\) to wrap the input, indicating that the next line is still the same;
  • Without escaping, keep the original string: print r'c: \ Program Files \ Python2.5 '. That is, add an r to the front;
  • Unicode string prefix u: u'hello Python! '

  

3. Chapter 2-List and metadata 3.1. Overview

The book says that Python contains six built-in sequences, which are commonly used in two types: List and metadata. But what are the six types? I searched all the blogs on the Internet. These are the words mentioned above. Finally, I found the Document on the official website.

Sequence Types- Str (string), Unicode, List), Tuple (tuples), Buffer, Xrange

Sequence refers to the arrangement of Ordered Sets. All sequences have internal functions such as index (-1 is the last element), sharding, addition, multiplication, membership, length, maximum and minimum. The list can be modified, but the tuples cannot. In general, the list can replace tuples. Sequences and mappings (such as dictionaries) are two main types of containers, and a set also belongs to the container.

Str, unicode: The two strings have been mentioned before;

List: list. For example, edward = ['panderen', 12];

Tuple: tuples.

Buffer: buffer object, such as string, array, and buffer. Buffer (object [, offset [, size]);

Xrange: It works the same as range (), but xrange returns an xrange object. Range returns a list object. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. That is to say, xrange does not store data at the same time. On the contrary, range stores data. Then range will open up a lot of space, especially when the data volume is large. Therefore, xrange may improve performance.

The following link summarizes some common types. Http://wuyuans.com/2013/04/python-data-type/

  

Type Type name Description
None Type (None) Null Object None
Numeric type Int Integer
Long Long Integer, any precision (python2)
Float Floating Point Number
Complex Plural
Bool Boolean (True or False)
Sequence type Str String
Unicode Unicode string (python2)
List List
Tuple Tuples
Xrange Integer Range created by xrang ()
Ing type Dic Dictionary
Set Type Set Variable set
Frozenset Immutable set

 

 

 

 

 

 

 

 

 

 

These are common types except sequences.

 

 

 

 

3.2. Basic operations
Operation Result
X in s TrueIf an itemSIs equalX, ElseFalse
X not in s FalseIf an itemSIs equalX, ElseTrue
S + t The concatenationSAndT
S * n, n * s NShallow copiesSConcatenated
S [I] I'Th itemS, Origin 0
S [I: j] SliceSFromIToJ
S [I: j: k] SliceSFromIToJWith stepK
Len (s) LengthS
Min (s) Smallest itemS
Max (s) Largest itemS

  

 

 

 

 

 

 

 

These are basic general operations of sequences.

 

 

 

 

Operation Result
S [I] = x ItemIOfSIs replacedX
S [I: j] = t SliceSFromIToJIs replaced by the contents of the iterableT
Del s [I: j] SameS [I: j] = []
S [I: j: k] = t The elementsS [I: j: k]Are replaced by thoseT
Del s [I: j: k] Removes the elementsS [I: j: k]From the list
S. append (x) SameS [len (s): len (s)] = [x]
S. extend (x) SameS [len (s): len (s)] = x
S. count (x) Return numberI'S for whichS [I] = x
S. index (x [, I [, j]) Return smallestKSuch thatS [k] = xAndI <= k <j
S. insert (I, x) SameS [I: I] = [x]
S. pop ([I]) SameX = s [I]; del s [I]; return x
S. remove (x) SameDel s [s. index (x)]
S. reverse ()

Reverses the itemsSIn place

>>> x = [1, 2, 3]>>> list(reversed(x))[3, 2, 1]

 

S. sort ([cmp [, key [, reverse])

Sort the itemsSIn place

X. sort (cmp)

X. sort (key = len), sorted by length

X. sort (reverse = True), reverse sorting

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Common sequence operations

 

 

 

 

 

 

  3.3. multipart

The START vertex is included in the returned result, and the end vertex is not included in the part.

  • Number [-3:] -- access from the third to the last to the end;
  • Number [:] -- returns all records and can be used to copy sequences;
  • Number [] -- The step size is 1;
  • Number [: 4] -- the first of every four elements;
  • Number [8: 3:-1] -- step 1, extract data from right to left;

 

3.4. Multiplication
  • 'Python' * 5, the result is 'pythonpythonpython '. It is equivalent to copying.
  • None is the built-in value of Python, indicating that nothing exists. However, the website must be located. Well... That is, the moukeng is not XX.

  

3.5. List
  • Name = list ('hello'), the result is ['h', 'E', 'l', 'l', 'O'];
  • ''. Join (name). The result is" Hello ";
  • Number [1] = 2, name [2:] = list ('ar '), modify the value;
  • Number [1:1] = [2, 3, 4], insert 2, 3, 4 Before number [1;
  • Number [] = []. The result is the same as del number.
  • Number. append (object), append is to add parameters as objects, such
  • 1 >>> number = [1,2,3];2 >>> number3 [1, 2, 3]4 >>> number.append([4,5])5 >>> number6 [1, 2, 3, [4, 5]]7 >>> number.extend([6,7])8 >>> number9 [1, 2, 3, [4, 5], 6, 7]

  

3.6. tuples

Define an object that contains a worthy tuples, x = (42 ,). Therefore

>>> 3*(40+2) 126>>> 3*(40+2,)(42, 42, 42)
>>> x = 1, 2, 3
>>> x
(1, 2 ,3)

 

4. Chapter 3 -- use strings 4.1. format the output
>>> print "Pi is: %.3f" % 3.141592653589793238462643383279Pi is: 3.142
4.2. string format conversion type
Flag Meaning
'#'

The value conversion will use the "alternate form" (where defined below ).

>>> print "Pi is: %#20.3f" % 3.141592653589793238462643383279Pi is:                3.142
'0'

The conversion will be zero padded for numeric values. Fill in with 0

>>> print "Pi is: %020.3f" % 3.141592653589793238462643383279Pi is: 0000000000000003.142
'-'

The converted value is left adjusted (overrides'0'Conversion if both are given). Left alignment

>>> print "Pi is: %-20.3f" % 3.141592653589793238462643383279Pi is: 3.142
''

(A space) A blank shocould be left before a positive number (or empty string) produced by a signed conversion.

Left-aligned integer

>>> print "Pi is: % 20.3f" % -3.141592653589793238462643383279Pi is:               -3.142>>> print "Pi is: % 20.3f" % 3.141592653589793238462643383279Pi is:                3.142>>> print "Pi is: % 20.3f" % +3.141592653589793238462643383279Pi is:                3.142>>> print "Pi is: %+20.3f" % 3.141592653589793238462643383279Pi is:               +3.142>>> print "Pi is: %+20.3f" % -3.141592653589793238462643383279Pi is:               -3.142
'+'

A sign character ('+'Or'-') Will precede the conversion (overrides a "space" flag ).

>>> print "Pi is: %+20.3f" % 3.141592653589793238462643383279Pi is:               +3.142

 

Conversion Meaning
'D' Signed integer decimal.
'I' Signed integer decimal.
'O' Signed octal value.
'U' Obsolete type-it is identical'D'.
'X' Signed hexadecimal (lowercase ).
'X' Signed hexadecimal (uppercase ).
'E' Floating point exponential format (lowercase ).
'E' Floating point exponential format (uppercase ).
'F' Floating point decimal format.
'F' Floating point decimal format.
'G' Floating point format. Uses lowercase exponential format if exponent is less than-4 or not less than precision, decimal format otherwise.
'G' Floating point format. Uses uppercase exponential format if exponent is less than-4 or not less than precision, decimal format otherwise.
'C' Single character (accepts integer or single character string ).
'R' String (converts any Python object usingRepr ()).
'S' String (converts any Python object usingStr ()).
'%' No argument is converted, results in'%'Character in the result.

 

Write it here first, read the book, and then write the dictionary, conditional statements, classes, and exceptions...


Which python version does the basic python tutorial support?

The basic tutorial corresponds to python2.6 which can be downloaded from the official python website.
Www.python.org/getit/
Python3.x is significantly changed compared with 2.x
If you use windows, you can download Python 2.7.2 Windows Installer
The difference between 2.7.2 and 2.6 is not very big. It has some characteristics of 3. x.

Install next one way. I will not talk about it in the book.

The first chapter of a basic python tutorial first describes how to install the fifth and sixth articles in python.

Terminal means the terminal. Because Python is cross-platform, you can understand it in terms of terminals.

In Windows, Start Menu --- run ----- CMD press Enter. This is the Dos interface, that is, the Terminal of Windows.

"The method for running python in Terminal is to input the program name and press the enter key ."

You have compiled a Python program named demo1, so you only need to enter demo1 and press Enter,
Then the program runs.

Related Article

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.