Basic grammar
Hello world!
Python Lower output Hello world! Let's write it as follows . The extension of the file is .py( for example : test.py).
print "Hello world!"
however , stay Python 3 Next , This writing is wrong . It should be written as follows .( later , Basic it is Python 2.7 To illustrate .)
print("Hello world!")
After completion , Execute the following command .
python test.py
stay Python in , Statements are separated by line breaks .
for example :
print "Hello" print "World"
similar Perl and PHP Writing , Use semicolon (;) Separation is also OK .
a = 5; b = 3; c = a + b print c
Statement to separate multiple lines of description , Use a backslash at the end of the line (\) To express .
total = 123 \ + 456 \ + 789
(...), [...], {...} Inside (,) The situation of (\) It can be omitted .
months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
notes (#)
from (#) To the end of the line is the comment content .
print "Hello" # Helloと Express します
“\” You can't comment later .
total = 123 \ # This annotation method is wrong + 456 # Here is the correct note
comma (,) You can write notes later .
months = [ 'Jan', 'Feb', 'Mar', 'Apr', # You can write notes 'May', 'Jun', 'Jul', 'Aug', # You can write notes 'Sep', 'Oct', 'Nov', 'Dec' ]
Indent
Perl, PHP adopt { ... } Represents a code block ,Python The bottom line is indented at the beginning of the line to indicate , Lines with the same number of spaces at the beginning of a line are treated as the same code block .
a = 3 if a == 5: print "AAA" # if Code block of statement print "BBB" # if Code block of statement print "CCC" # Do not belong to if Code block of statement
The indentation at the beginning of a line is usually used 4 A space .tab It's fine too .
[ blank ][ blank ][TAB]print "AAA" # 8 Blank text
code (coding:)
It contains Chinese characters ,ASCII Outside the text of the script 1 OK or the second 2 That's ok , Specify the encoding type as follows . Ignore case .
# coding: utf-8 print "Hello world" # Here you can enter noon and other non ASCII The characters of .
Consider and Emacs The following wording is also accepted .
# -*- coding: utf-8 -*-
Other coding types are :
# coding: utf-8
# coding: Shift_JIS
# coding: EUC-JP
# coding: cp932