語言特性
高級(jí)編程語言一般有兩大家族站宗,一是編譯性語言,一是解釋性語言益愈。編譯性語言諸如C梢灭,C++夷家,Java等,需要編譯成特殊的可執(zhí)行文件敏释,在指定的環(huán)境中執(zhí)行库快,如Java編譯后是.class文件,需要在Java虛擬機(jī)(JVM)中執(zhí)行钥顽。解釋性語言也叫腳本語言义屏,能直接在指定環(huán)境(解釋器)執(zhí)行的語言。Python屬于解釋性語言蜂大,只要有Python解釋器的環(huán)境兼可執(zhí)行闽铐。
注釋
Python的注釋支持單行注釋,多行注釋奶浦。單行注釋一般用井號(hào)(#)開頭兄墅,多行注釋用三單引號(hào)(''' 注釋內(nèi)容 ''')或三雙引號(hào)("""注釋內(nèi)容""")。好的注釋能增加代碼的可讀性和可維護(hù)性澳叉,注釋盡量標(biāo)準(zhǔn)和正規(guī)隙咸。個(gè)人習(xí)慣一般在文件的頭部要有該文件的功能描述型注釋,推介再加入作者及日期等成洗,根據(jù)自己的情況進(jìn)行注釋五督。
#! /usr/bin/python3
# -*- coding: utf-8 -*-
'''
這里是注釋泌枪,可以說明這個(gè)腳本的功能描述
功能:這是一個(gè)測(cè)試文件
作者:Darker
日期:2019年10月22日
'''
print("Hello Python")
print(str(__name__))
"""
Python文件既可以獨(dú)立運(yùn)行概荷,也可以當(dāng)做模塊導(dǎo)入到其他文件秕岛。
當(dāng)導(dǎo)入到其他的腳本文件的時(shí)候碌燕,此時(shí)__name__的名字其實(shí)是導(dǎo)入模塊的名字,不是’__main__’继薛,
main代碼里面的就不執(zhí)行了修壕。
"""
if __name__ == '__main__':
print("Main 執(zhí)行了")
pass
第一行是“#! /usr/bin/python3”,這是是用來說明腳本語言是python遏考,要用/usr/bin下面的程序(工具)python3這個(gè)解釋器慈鸠,來解釋運(yùn)行python腳本的,如果環(huán)境變量中指定了Python解析器灌具,該行代碼可以不用青团。
字符集
Python基本支持所有字符集,字符集在代碼首行或第二行約定咖楣,形式如下:
# -*- coding: utf-8 -*-
代碼塊
Python與其他編程語言最直接的分別在于Python的代碼塊(或叫代碼組)是按縮進(jìn)區(qū)分督笆,相同的代碼塊有相同的縮進(jìn)進(jìn)度。其他的編程語言如C诱贿,Java是通過大括號(hào)({})進(jìn)行塊區(qū)分娃肿。如下代碼:
# -*- coding: utf-8 -*-
'''
這里是注釋咕缎,可以說明這個(gè)腳本的功能描述
功能:這是一個(gè)測(cè)試文件
作者:Darker
日期:2019年10月22日
'''
def add(a,b):
return a+b
def doublestr(s,t):
print(str(s) * t)
"""
Python文件既可以獨(dú)立運(yùn)行,也可以當(dāng)做模塊導(dǎo)入到其他文件料扰。
當(dāng)導(dǎo)入到其他的腳本文件的時(shí)候凭豪,此時(shí)__name__的名字其實(shí)是導(dǎo)入模塊的名字,不是’__main__’晒杈,
main代碼里面的就不執(zhí)行了嫂伞。
"""
if __name__ == '__main__':
print("Main 執(zhí)行了")
add(1,2)
doublestr('godbirds\n',2)
pass
上面代碼塊內(nèi)定義了兩個(gè)函數(shù),在main方法中調(diào)用了桐智,因?yàn)镻ython執(zhí)行是逐行從上往下執(zhí)行末早,所以在main方法內(nèi)部調(diào)用的方法或?qū)ο蟊仨毷且崖暶鞯模駝t會(huì)報(bào)出:NameError: name 'XXX' is not defined的錯(cuò)誤说庭。把doublestr方法定義在main的后面則會(huì)出現(xiàn)這種情況然磷。
標(biāo)識(shí)符
標(biāo)識(shí)符是由字母、下劃線開頭的由字母刊驴、數(shù)字姿搜、下劃線組成的區(qū)分大小寫的字符串。與Java一樣捆憎,字符串命名盡量見文識(shí)意舅柜。
關(guān)鍵字
關(guān)鍵字是語言內(nèi)部設(shè)定的具有一定意義的關(guān)鍵詞匯,不可用于命名為標(biāo)識(shí)符或函數(shù)名等躲惰≈路荩可用代碼查看系統(tǒng)內(nèi)部的關(guān)鍵字信息:
# -*- coding: utf-8 -*-
import keyword
print("關(guān)鍵字為:")
print(keyword.kwlist)
輸出為:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
數(shù)據(jù)類型
數(shù)據(jù)類型包括:Number 數(shù)字,String 字符串础拨,List 列表氮块,Set 集合、Tuple 元組诡宗,Dictionary 字典滔蝉。數(shù)字、字符串塔沃、元祖定義后不可修改蝠引。列表、集合蛀柴、字典可根據(jù)下標(biāo)或者鍵進(jìn)行讀取和修改螃概。
type(1) # 輸出<class 'int'>
type(1.2) # 輸出<class 'float'>
type(True) # 輸出<class 'bool'>
type(False) # 輸出<class 'bool'>
type(1+1j) # 輸出<class 'complex'>
type(bool(0)) # 輸出<class 'bool'>
print(bool(1)) # 輸出True
type([1,2,'str',True]) # 輸出<class 'list'>
type({12,3,'str'}) # 輸出 <class 'set'>
type((1,2,3,'str',True)) # 輸出 <class 'tuple'>
type({'name':'wping','age':18,1:2019}) # 輸出<class 'dict'>
- 數(shù)字
數(shù)字包括:int 整數(shù)、float 浮點(diǎn)鸽疾、bool 布爾吊洼、complex 復(fù)數(shù)
無小數(shù)點(diǎn)是整數(shù),帶小數(shù)點(diǎn)是浮點(diǎn)肮韧,0為整數(shù)融蹂,1.0浮點(diǎn)旺订,a+bj是復(fù)數(shù),a實(shí)數(shù)超燃,b虛數(shù)区拳,j虛數(shù)單位,復(fù)數(shù)詳見百科意乓,本文不做具體描述和使用樱调。 - 布爾
這里布爾在數(shù)字類型里面單獨(dú)拿出來主要是Python3開始用關(guān)鍵字True 和 False 表示,其底層值依然還是0和1(非零即True)届良。
# 1笆凌、證明 True = 1
print(True == 1) # 輸出 True
print(True == 0) # 輸出 False
print(True == 2) # 輸出 False
# 2、證明 False = 0
print(False == 0) # 輸出 True
print(False == -1) # 輸出 False
# 3士葫、證明非0即True
bool(1) # 輸出 True
bool(2) # 輸出 True
bool(100.2) # 輸出 True
bool(0) # 輸出 False
bool(-1) # 輸出 True
- 字符串
字符串用單引號(hào)或雙引號(hào)或str()函數(shù)創(chuàng)建乞而,Python中單引號(hào)和雙引號(hào)使用完全相同。備注:字符串是特殊的元組慢显。
a = 'str' # 單引號(hào)創(chuàng)建
b = "str" # 雙引號(hào)創(chuàng)建
c = str('str') # 函數(shù)創(chuàng)建
print(type(a)) # 輸出 <class 'str'>
print(type(b)) # 輸出 <class 'str'>
print(type(c)) # 輸出 <class 'str'>
print(a == b) # 輸出 True
print(a == b == c) 輸出 True
- 列表
列表是使用中括號(hào)[] 或list() 函數(shù)創(chuàng)建爪模,與Java的列表(List)或數(shù)組類似,有序的可重復(fù)的數(shù)據(jù)組合荚藻。通過下標(biāo)訪問屋灌。
a = [1,'a',"A",'A'] # 中括號(hào)創(chuàng)建
b = list((1,'a',"A",'A')) # 函數(shù)創(chuàng)建
print(type(a)) # 打印a的類型,輸出 <class 'list'>
print(type(b)) # 打印b的類型应狱,輸出 <class 'list'>
c = a+b # 兩個(gè)數(shù)組直接相加 或者 list(set(a).union(set(b)))
print(c) # 打印相加后的值共郭,輸出 [1, 'a', 'A', 'A', 1, 'a', 'A', 'A']
d = a-b # 不支持兩個(gè)結(jié)合相減
'''
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
'''
- 集合
集合用大括號(hào){}或 set()函數(shù)創(chuàng)建,與Java的Set 集合類似疾呻,無序的不可重復(fù)的數(shù)據(jù)組合除嘹。備注:創(chuàng)建空集合必須使用set()函數(shù),不能用空的大括號(hào)創(chuàng)建罐韩,空的大括號(hào)是創(chuàng)建字典的語法憾赁。
a = {'a',1,True,None} # 中括號(hào)創(chuàng)建集合
b = {'b',2,False,None} # 中括號(hào)創(chuàng)建集合
s = set(('b',2,False,None)) # 函數(shù)創(chuàng)建集合
print(type(a)) # 打印a的類型污朽,輸出<class 'set'>
print(type(b)) # 打印b的類型散吵,輸出<class 'set'>
print(type(a)==type(b)) # 輸出 True
c = a+b # 不支持集合直接相加
"""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'set' and 'set'
"""
c = set(a).union(set(b)) # 集合求并集
print(c) # 輸出 {False, 1, 'b', 2, 'a', None}
print(type(c)) # 輸出<class 'set'>
d = list(set(a).union(set(b))) # 集合求并集轉(zhuǎn)為列表
print(d) # 輸出 [False, 1, 'b', 2, 'a', None]
e = set(a).intersection(set(b)) # 集合求交集
print(e) # 輸出 {None}
f = set(a).difference(set(b)) # 集合求差集
print(f) # 輸出 {1, 'a'}
print(type(f)) # 差集類型輸出<class 'set'>
g = list(set(a).difference(set(b))) # 集合求差集轉(zhuǎn)為列表
print(g) # 輸出[1, 'a']
print(type(g)) # 輸出差集類型<class 'list'>
- 元組
元組用括號(hào)或tuple()函數(shù)創(chuàng)建,表明一些列不可根據(jù)修改的組合蟆肆,有別于其他的編程語言矾睦,但其內(nèi)部可存儲(chǔ)可變的集合或列表或字典等可變的類型。
a = ('a',1,True) # 括號(hào)創(chuàng)建元組
b = tuple(('a',1,False)) # 函數(shù)創(chuàng)建元組
print(type(a)) # 打印元組類型炎功,輸出<class 'tuple'>
print(type(a) == type(b)) # 打印元組類型是否相等枚冗,輸出True
c = ('a') # 定義單一字符串元組
print(type(c)) #打印元組類型,輸出<class 'str'> 故字符串是特殊的元組
print(a[0]) # 根據(jù)下標(biāo)獲取元組蛇损,輸出 a
d = a[1] # 獲取元組值賦值給d
print(d) # 打印元組赁温,輸出1
a[1] = 2 # 修改元組內(nèi)部值坛怪,錯(cuò)誤,故元組內(nèi)部值不可變
'''
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
'''
- 字典
字典是無序的由鍵值對(duì)組成的數(shù)據(jù)組合股囊,等同于Java的Map袜匿。通過鍵取值。
a = {'a':1,'x':True} # 中括號(hào)創(chuàng)建
b = dict({'b':c,'x':False}) # 函數(shù)創(chuàng)建
如下展示了元組不可變和存儲(chǔ)可變數(shù)據(jù)類型案例
備注:>>>后代表Shell命令行稚疹,無符號(hào)行表是輸出結(jié)果居灯,后面不再做解釋
>>> t = tuple((1,2,'str',[1,2,3],{'a',1,2,3}))
>>> print(t)
(1, 2, 'str', [1, 2, 3], {1, 2, 3, 'a'})
>>> t1 = t[0]
>>> print(t1)
1
>>> t2 = t[3]
>>> print(t2)
[1, 2, 3]
>>> t2[1] = 'change'
>>> print(t2)
[1, 'change', 3]
>>> print(t)
(1, 2, 'str', [1, 'change', 3], {1, 2, 3, 'a'})
>>> t[2] = 'str_chg'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
模塊導(dǎo)入
導(dǎo)入某個(gè)模塊的腳本,與Java import 類似内狗。導(dǎo)入后可在該文件中調(diào)用導(dǎo)入的模塊內(nèi)部的類和函數(shù)怪嫌,語法如下:
#導(dǎo)入整個(gè)模塊A
import A
#導(dǎo)入整個(gè)模塊A的所有函數(shù)
from A import *
#導(dǎo)入模塊A的a函數(shù),別名為a
import A.a as a
#導(dǎo)入模塊A的 a柳沙、b岩灭、c函數(shù)
from A import a,b,c
輸入輸出
輸入:input("請(qǐng)您錄入") 執(zhí)行函數(shù)后等待輸入設(shè)備輸入信息
輸出:print("打印的內(nèi)容") 打印出相應(yīng)的內(nèi)容
至此入門基礎(chǔ)語法介紹完畢,還有一些不太常用的語法會(huì)在后面涉及到的時(shí)候提及赂鲤。后面會(huì)再深入基礎(chǔ)篇川背,對(duì)數(shù)據(jù)類型,邏輯運(yùn)算蛤袒,流程控制以及異常捕獲等進(jìn)行學(xué)習(xí)和探討熄云。