Python Learning Note-day01

Source: Internet
Author: User
Tags arabic numbers

Version comparison of Python

CPython: Official version, using C implementation, the most widely used, Linux comes with,

Jython:python Java implementation, interoperability with the Java language is higher than other Python implementations

Ironpython:python C # Implementation, compiles the Python code into C # bytecode, and then runs.

The python implementation of Pypy:python is faster than CPython.



########################################################

Installation

Win under install. Directly download the installation package directly, if you want to execute the python command directly under CMD, you need to configure environment variables.

Configuration is: Take Win7 as an example

Computer--right---Properties--Advanced system settings--environment variables--in the system variable, find path

Double-click and add Python's installation path, note that the delimiter is a semicolon, and after saving, open cmd again




l########################################################

Install under Linux

If the system comes with a lower version (such as the CENTOS6 series comes with Python version 2.6.X), download the source package for compilation and installation, as follows:

Taking centos6.4 as an example

Open http://www. python. org for Python website, download source package, currently the latest version is 2.7.10

Https://www.python.org/ftp/python/2.7.10/Python-2.7.10.tgz


Yum install gcc #安装以来报tar XF python-2.7.10.tgz #解压源码包cd Python-2.7.10/configure--prefix=/usr/local/python27 Makemake installmv/usr/bin/python/usr/bin/python2.6ln-s/usr/local/bin/python2.7/usr/bin/python


由于centos6.3需要python2.6的支持,使用python2.7会出问题

所以需要修改yum配置文件中的python指向

Vi/usr/bin/yum


将头部 #!/usr/bin/python 修改为 #!/usr/bin/python2.6



########################################################

The first sentence of Python

Vim hello.py

#文件结尾建议以. Py end, one is to facilitate the identification of the file, and the second is called by other Python files, non-. py file ends cannot generate a PYc file (. pyc file is a Python script bytecode file)

#!/usr/bin/env python   #linux系统下脚本文件的shebang设置,,    when executed in  ./script  mode                                         #可以为脚本指定默认的解释器 # -*- coding:utf-8 -*-    #由于python脚本默认是ASCII编码, The text will be shown with an ASCII to                                         #系统默认编码的转换, there will be an error: Syntaxerror: non-ascii character.                                         #需要在代码文件的第一行或第二行添加编码指示       &Nbsp;                              print  "Hello world"


Save exit after completion

Execute script

Python hello.py


Attention:

1.#-*-Coding:utf-8-*-Another way of writing, that is, # Coding:utf-8, it is important to note that the latter may sometimes not be effective (not met, but there is this possibility), so the recommended wording is the first.

2. File encoding problem: The computer at the beginning of the first time only English, and a byte will be able to represent all the English and many of the control symbols (the underlying ASCII can represent 128 characters, for international standards, extended ASCII extended to 255, but no longer an international standard, The biggest disadvantage of ASCII is that it can only display 26 basic Latin letters, Arabic numbers, and English punctuation marks, so it can only be used to display modern American English; later, the computer world soon joined other languages, but ASCII was unable to meet the requirements, and at this time there were other file encodings, not listed), because the characters involved more and more, such as Chinese, this period also has a lot of other file encoding (if each region a set of file encoding, local use no problem, but to the network environment, there will be problems), and then everyone felt such a condom of the character set too much, it made a universal code, That is, Unicode, and become a standard in the industry, Unicode uses a minimum of two bytes to encode a character, when used, if you want to represent ASCII characters, there will be a waste of resources, because the ASCII character as long as 1 bytes can be represented, and then, Utf-8 is being researched, Utf-8 is a variable-length character encoding that can be used to represent any character in the Unicode Standard, and the first byte in the encoding is still compatible with ASCII, and Utf-8 uses one to four bytes to represent one character.


————————————————————————————

Comments:

Single-line comment: Start with #

#单行注释

Multiline Comment: Triple quotation mark (can be single or double quotation marks)

Cases:

”“”

Multi-line comments

“”“

But #!/usr/bin/env python and #-*-Coding:utf-8-*-because of a special effect not counting annotations

————————————————————————————

The difference between quotation marks

Both single and double quotes can be used to represent strings, but they must appear in pairs,

There is a special case

"Let's Go"

' Let\ ' go ' #字符串中的 \ means escape

These two cases are equivalent,



########################################################


about how Python scripts are executed

Python files are divided into three categories

Built-in Modules

Third-party class libraries

Customization files


Python files in the execution process

First, read the file from disk, load it into memory, perform lexical analysis--------parse--------

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201510/425762-20151024160748145-1165720810. PNG "height=" 348 "width=" 619 "/>

The purpose of the PYc file is to speed up the execution of the program, similar to the Java class file,

During the execution of the Python script, the compiled results will only be present in memory, and when executed, the results will be saved to the PYc file.

This will be compiled again next time, loading the PYc file directly into memory.

It is important to note that when hello.py When the Hello.pyc file is present, Python will first determine whether the Hello.pyc file is a direct compilation of hello.py, and if the hello.py file has changed, then Python compiles the hello.py file again and generates the HELLO.PYC file; If the hello.py has not changed, the Hello.pyc file is loaded directly.



#############################################################

Get Script Parameters

Python provides a built-in module for getting script parameters, SYS.ARGV

Use the following method

VI login.pyimport sysprint SYS.ARGV

Perform

Python login.py 123


[' login.py ', ' 123 '] #结果, return a list (detailed description of the list later),



##############################################################

Variable

Definition: A pointer to a memory space address (the pointer may not be accurate, actually giving a memory space a name)

Usage rules: 1. Variable name intelligence is alphanumeric underline

2. The first character cannot be a number

3. When declaring a variable, you need to avoid the keyword

4. Variable Letter Case

Note: There is a mechanism for the object buffer pool in Python (the purpose of the buffer pool is to speed up the execution of the program), for small integers [-5,257] , the system has been initialized well, can be used directly, and for large integers, the system has requested a space in advance, Create a large integer object in the space when needed. Here only to do a brief introduction, detailed machine reference Python source (memory mechanism)

>>> a=3>>> b=3>>> ID (a); ID (b) 3603280836032808>>> c=900>>> d=900> >> ID (c); ID (d) 3631536036315408



##############################################################

Input/Output

Raw_input () #获取用户输入; another way to get the user input is input (), the difference is that the former directly read the console input, can be any character, the latter would like to read a valid Python expression, that is, the input string should be quoted. Input () is essentially implemented by using raw_input (), just call the eval () function after calling late Raw_input (). Therefore, it is recommended to use Raw_input () unless there is a special need for input ().


Print #打印内容



###############################################################

Process Control and Indentation

Python uses indentation to group code

Branch statement if

The first method of use

If Condition:pass


The second method of use (if .... else ...). )

The If condition:passelse:pass# Pass is a placeholder that means nothing is done, and when executed to the PASS statement, no action is taken to perform the third use of the method (if: Elif .... else)
If Condition:passelif Condition:passelse:pass



#######################################

loop control (for while)


For element in Setofobject:

Print element

[Else:

Pass


The For loop is used to traverse an object and also has an optional else statement block that comes with it.



While condition:

Pass


It is important to note that while the condition is true, the while is executed until the condition is false


When using a looping statement, it involves two statements break and continue

Break: Jump out of the loop

Continue: End as secondary cycle

Break example: For I in range (5): If i==3 break print i output result: 012


Continue example:

For I in range (5): If i==3 contine print i output result: 0124


Range () is used to generate a sequence that will be discussed later.




########################################################

Basic data types

Number (int long float complex), string, list, tuple, Boolean, dictionary

Type (VAR) # for viewing variable types


---------------------------------------------------------------------------------------------------------

String:

Strings are immutable objects, there are two ways to connect, one is to use +, one is to use join ()

---------------------------------------------------------------------------------------------------------

Connection of strings

When using + to concatenate two strings, a new string is generated, the resulting string needs to be re-requested for memory, and the speed slows down when multiple strings are added consecutively

astring = "". Join ("A", "B", "C", "D", "E",........) For the join () method There is only one memory request, and the speed is fast

---------------------------------------------------------------------------------------------------------

Formatting of strings

There are two ways of formatting a string

First Kind%

Cases:

var = ' I am%s '% ' hal,age%d '
var = ' I am%s,age%d '% (' Hal ', 12)
Or
var% (' Hal ', 12)


%s string
%d numbers


The second type. Format ()

var = ' I am {0},age {1} '
Name.fornamt ("Alex", #推荐使用该方法), relatively high efficiency

---------------------------------------------------------------------------------------------------------

Manipulation of strings

String index starting from 0
Var= ' Qwe '
VAR[0]
Var[0:2] takes characters starting from 0 that are less than 2
Var[0:] Take from 0 to last
Var[-1] Last character
VAR[0:-1] 0 before the last one
Var[::-1] string inversion

Len (Var) gets the string length

String removal space
Var.strip () Remove two spaces
Var.lstrip () Remove left space
Var.rstrip () Remove the right space

String segmentation
Var= "Alex,tony,eric"
Var.split (', ') #不指定分隔符时, the default is a space delimiter






---------------------------------------------------------------------------------------------------------

List

List can be modified
Create a list
Name_list = ["AAA", "BBB"]
Or
Name_list = List (["AAA", "BBB"]) #本质上是上面调用该语句. That is List ()


Shards are similar to strings


Additional
Append ()
List.append ("AAA")

Delete
Del List[n]

Len (list) Gets the length

Join () ' _ '. Join (list) _ as delimiter


Contains in
' A ' in list returns a Boolean value

Cycle

For I in list:

Print I



---------------------------------------------------------------------------------------------------------

Tuple

("A", "B")
Tuples are not modifiable, others are similar to lists


---------------------------------------------------------------------------------------------------------

Dict Dictionary

Key-value pairs, dictionaries are unordered
{Key:value1,name:value2,age:value3,...}

For Key,value in Dict.items ():
Print Key,value


Dict.keys () All values
Dict.values () All keys
Dict.items () all key-value pairs, just for loop use


---------------------------------------------------------------------------------------------------------

Set

Unordered set of elements that are not duplicated


---------------------------------------------------------------------------------------------------------

Report

Arithmetic operators

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201510/425762-20151025004451692-544714036. PNG "height=" 207 "width=" 649 "/>

Comparison operators

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201510/425762-20151025004535395-2018056438. PNG "height=" 229 "width=" 647 "/>

Assignment operators

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201510/425762-20151025004625020-515390534. PNG "height=" 228 "width=" 645 "/>

logical operators

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201510/425762-20151025004829864-1676917934. PNG "height=" width= "645"/>

Member operations

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201510/425762-20151025004934286-1134210223. PNG "height=" width= "649"/>

Identity operations

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201510/425762-20151025005015567-214206984. PNG "height=" width= "646"/>

Bit arithmetic

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201510/425762-20151025005136817-1018821016. PNG "height=" 177 "width=" 645 "/>

Operator Precedence

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/425762/201510/425762-20151025005448536-1963442899. PNG "height=" 358 "width=" 649 "/>





##################################

Initial knowledge of text manipulation


F=file ("path", mode) #或者 open ("path", mode)
F.read ()
F.close () Close file

Read () The file reads the memory in full
ReadLines () reads the file fully into memory and returns a list in a behavior-delimited order.
Xreadlines () One line read in, deprecated
For lines in F:xreadlines method, one line at a time
Write () writes to file
WriteLine () writes one line at a line


Mode
R Read-only mode to open a file
W Write-only mode to open file

A Append mode open file

w+ read-write mode open file







Personal blog Address

Http://www.timesnotes.com

Address of this article

http://www.timesnotes.com/?p=68



This article is from the "'ll Notes" blog, so be sure to keep this source http://timesnotes.blog.51cto.com/1079212/1706463

Python Learning Note-day01

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.