編碼格式
- 默認(rèn)情況下,Python 3 源碼文件以 UTF-8 編碼,所有字符串都是 unicode 字符串
# -*- coding=utf-8 -*-
# -*- coding: cp-1252 -*-
^[ \t\v]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)
標(biāo)識符
- 第一個(gè)字符必須是字母表中字母或下劃線'_';
- 標(biāo)識符的其他的部分有字母、數(shù)字和下劃線組成;
- 標(biāo)識符對大小寫敏感;
Python保留字
- 保留字即關(guān)鍵字,不能把關(guān)鍵字用作任何標(biāo)識符名稱 ;執(zhí)行Python命令查看Python保留字
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', '
def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'retu
rn', 'try', 'while', 'with', 'yield']
>>>
注釋
# Python單行注釋
- 多行注釋使用多個(gè) # 或者 使用''' 和 """ 包裹
# 多行注釋
# 多行注釋
# 多行注釋
'''
多行注釋
多行注釋
多行注釋
'''
"""
多行注釋
多行注釋
多行注釋
"""
輸出語句
print("Hello World!")
- print 默認(rèn)輸出是換行的,如果要實(shí)現(xiàn)不換行需要在變量末尾加上 end="":
print("Hello",end="")
print("World")
代碼塊的表示
- Python 中使用縮進(jìn)來表示代碼塊,不需要使用大括號({});
if True:
print ("True")
else:
print ("False")
- 縮進(jìn)的空格數(shù)是可變的,但是同一個(gè)代碼塊的語句必須包含相同的縮進(jìn)空格數(shù);如果縮進(jìn)的空格數(shù)不一致,會導(dǎo)致運(yùn)行錯(cuò)誤:
if True:
print ("True")
else:
print ("Answer")
print ("False") # 縮進(jìn)不一致,會導(dǎo)致運(yùn)行錯(cuò)誤
多行語句表示
- Python中通常是一行一條語句,但如果語句很長,我們可以使用反斜杠()來實(shí)現(xiàn)多行語句;
total = item_one + \
item_two + \
item_three
- 特殊情況下,如在 [], {}, 或 () 中的多行語句,不需要使用反斜杠();
number = ['1', '2', '3',
'4', '5']
同一行顯示多條語句
- Python可以在同一行中使用多條語句,語句之間使用分號(;)分割;
print ("Hello");print ("World");print ("!");
多個(gè)語句構(gòu)成代碼組
- 縮進(jìn)相同的一組語句構(gòu)成一個(gè)代碼塊,稱之代碼組;像if、while、def和class這樣的復(fù)合語句,首行以關(guān)鍵字開始,以冒號( : )結(jié)束,該行之后的一行或多行代碼構(gòu)成代碼組。我們將首行及后面的代碼組稱為一個(gè)子句(clause)
if expression :
suite
elif expression :
suite
else :
suite
空行
- 函數(shù)之間或類的方法之間用空行分隔,表示一段新的代碼的開始;
數(shù)據(jù)類型
- python中數(shù)有四種類型:整數(shù)、長整數(shù)、浮點(diǎn)數(shù)和復(fù)數(shù)。
- 整數(shù), 如 1
- 長整數(shù) 是比較大的整數(shù)
- 浮點(diǎn)數(shù) 如 1.23、3E-2
- 復(fù)數(shù) 如 1 + 2j、 1.1 + 2.2j
字符串
- python中使用單引號或者雙引號定義一個(gè)字符串;
name = "SiberiaDante"
name = 'SiberiaDante'
- 使用三引號('''或""")可以指定一個(gè)多行字符串;
info = ''' name is SiberiaDante,
age is 18,
gender is man'''
info = """ name is SiberiaDante,
age is 18,
gender is man"""
- 引號可以使用轉(zhuǎn)義符 ''標(biāo)識;
# 輸出結(jié)果:name is "SiberiaDante"
print("name is \"SiberiaDante\"")
# 輸出結(jié)果:name is \"SiberiaDante\"
print(R"name is \"SiberiaDante\"")
- python允許處理unicode字符串,加前綴u或U, 如 u"this is an unicode string"。
- 字符串是不可變的。
import 與 from...import
- 在 python 用 import 或者 from...import 來導(dǎo)入相應(yīng)的模塊。
- 將整個(gè)模塊(somemodule)導(dǎo)入,格式為: import somemodule
- 從某個(gè)模塊中導(dǎo)入某個(gè)函數(shù),格式為: from somemodule import somefunction
- 從某個(gè)模塊中導(dǎo)入多個(gè)函數(shù),格式為: from somemodule import firstfunc, secondfunc, thirdfunc
- 將某個(gè)模塊中的全部函數(shù)導(dǎo)入,格式為: from somemodule import *