One, the first Python code
1. Open the Python shell
--》
2. Enter print ("Hello world!"), enter enter
3. At this point, our first Python program is finished, and the function of this program is to output "Hello world!" to the console.
The python internal execution process is as follows:
Second, create code files, execute Python program
1. Create the file a1.py and enter the following code
# ! /usr/bin/python Print ("Hello world! ")
2. Program Description
1) The first line of code: #/usr/bin/python tells the system which interpreter to use to execute this file
2) The second line of code: console printout "Hello world!"
3. Execution of documents
Open the Windows console, enter
python E:\python\a1.py # E:\python\a1.py to file path
After enter, the execution results are as follows:
Third, the Code
Modify the contents of the a1.py and save as a2.py
# !/usr/bin/python Print (" Hello, python")
Re-execute a2.py
Run error, wrong reason: coding error, file default encoding is ASCII, and ASCII does not support Chinese
Workaround: Modify the code as follows and save as a3.py
# !/usr/bin/python # -*-coding:utf-8-*- Print (" Hello, python")
Re-execute a3.py
File execution succeeded.
Note: python2.7 default ASCII encoding, python3 default UTF-8 encoding
1. python2.7 need to decode Chinese to Unicode and encode again as Utf-8
# !/usr/bin/python # -*-coding:utf-8-*- " Hello " # first decode "Hello" to UnicodeTemp_unicode = Temp.decode ("utf-8")# then encode the decoded "Hello" to gbkTEMP_GBK = Temp_unicode.encode ("gbk") Print(TEMP_GBK)
Process
2. Python3 can directly speak Chinese code as Utf-8, omit intermediate to Unicode process
# !/usr/bin/python # -*-coding:utf-8-*- " Hello " # encode "Hello" directly to GBKTEMP_GBK = Temp_unicode.encode ("gbk")Print (TEMP_GBK)
Other: Encoding classification: ASCII, GB2312, GBK, ANSI, Unicode, UTF-8, UTF-16 and UTF-32 (refer to Baidu Encyclopedia: code)
Iv. notes
Single-line Comment: Use "#", or # Annotated content
Multi-line Comment: Use ' annotated content '
Five, module import
1. If there are a.py file contents as follows
Print ("test import")
2. The contents of the b.py file are as follows
Import a Print ("import End")
"Import a" will import a.py content into b.py, run b.py, the results are as follows
Import Import End
Note: If you import the a.py file for the first time, a A.PYC file will be generated (the bytecode file that was compiled by Python program)
Python Learning (ii)--python Introduction