[toc]
# 基礎特性
```python
# Python語句中一般以新行作為為語句的結束符。多行顯示要通過 \
num1 = 1
num2 = 2
num3 = 3
total = num1 + \
num2 + \
num3
print("total is : %d"%total)
# 輸入輸出
name = input('please enter your name:');
print('hello,',name);
# 刷新熒幕,實時輸出
import time
import sys
for i in range(5):
print(i, end=' '),
sys.stdout.flush() # 加這句就能每秒輸出
time.sleep(1)
# 在Python里常量是可以改變的
PI = 3.14;
PI = 3.14159;
# 刪除變量
del d
```
## 運算符
### 運算符優先級
```
#運算優先級由低到高
Lambda
邏輯運算符: or
邏輯運算符: and
邏輯運算符:not
成員測試: in, not in
同一性測試: is, is not
比較: <,<=,>,>=,!=,==
按位或: |
按位異或: ^
按位與: &
移位: << ,>>
加法與減法: + ,-
乘法、除法與取余: *, / ,%
正負號: +x,-x
```
### 短路運算符
```python
a=1
b=2
c1 = a and b # 前面為false就一定為false,不必執行第二個
c2 = a or b # 前面為true就一定為true,不必執行第二個
print(c1,c2)
```
### 三目運算符(三元表達式)
> Python不支持三目運算符,不過有以下相對應的支持
```python
# x if condition else y
# 為真時的結果 if 判斷條件 else 為假時的結果(注意,沒有冒號)
# 斐波那契數列
def fn(n):
return n if n < 2 else fn(n-1)+fn(n-2)
# np.where(判斷條件,為真時的處理,為假時的處理)
# np為numpy對象 pip install --upgrade numpy
# x = np.where(x%2==1, x+1, x)
import numpy as np
x = 0
x = np.where(x%2==1, x+1, x)
```
## 字符串
```python
# 字符串占位符替換,如果字符串里面有%,就要用%%來表示
# %2d,不足2位,前面補空格;%02d,不足2位,前面補0;
# 其他的還有%s,%f,%r
str = '%2d-%02d' % (3, 1)
print(str)
print('%.2f' % 3.1415926)
# %r
text = "I am %d years old." % 22
print("I said: %s." % text) # I said: I am 22 years old.. %s用str()方法處理對象
print("I said: %r." % text) # I said: 'I am 22 years old.'. %r用rper()方法處理對象
import datetime
d = datetime.date.today()
print("%s" % d) # 2018-06-12
print("%r" % d) # datetime.date(2018, 6, 12) %r打印時能夠重現它所代表的對象
# 轉義與不轉義
print('\\\t\\');
print(r'\\\t\\'); # r''表示''內部的字符串默認不轉義
# ''' : 多行字符串
str = '''line1
line2 \\
line3
''';
print(str);
# r: 非轉義的原始字符串
str = r'''line1 we \\
line2
line3
''';
print(str);
# u: 表示unicode字符串,后面字符串以 Unicode 格式 進行編碼,一般用在中文字符串前面,防止因為源碼儲存格式問題,導致再次使用時出現亂碼。在python3中可以忽略
str = u"我是含有中文字符組成的字符串。"
# b: bytes Python3里默認的str是(Python2里的)unicode, bytes是(Python2)的str, b前綴代表的就是bytes。 Python2里, b前綴沒什么具體意義, 只是為了兼容Python3的這種寫法。
# 字符串repeat
'str1'*10 # str1str1str1str1str1str1str1str1str1str1
# format 格式化函數
"{} {}".format("hello", "world") # 不設置指定位置,按默認順序
"{0} {1}".format("hello", "world") # 設置指定位置
"{1} {0} {1}".format("hello", "world") # 設置指定位置 'world hello world'
print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com"))
site = {"name": "菜鳥教程", "url": "www.runoob.com"}
print("網站名:{name}, 地址 {url}".format(**site))
```
## 條件判斷
在Python中,None、空列表[]、空字典{}、空元組()、0等一系列代表空和無的對象會被轉換成False。除此之外的其它對象都會被轉化成True。
在命令if not 1中,1便會轉換為bool類型的True。not是邏輯運算符非,not 1則恒為False。因此if語句if not 1之下的語句,永遠不會執行。
```python
# 判斷 沒有===,用is代替===
1 == '1' # False
age = 19
if age > 30:
print('中')
elif age > 18:
print('成')
else:
print('小')
birth = input('birth: ')
birth = int(birth) # str不能直接和整數比較,必須先把str轉換成整數。
if birth < 2000:
print('00前')
else:
print('00后')
```
## 循環
```python
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
if(x == 5): continue
if(x == 10): break
sum = sum + x
# 4950
list = list(range(100)) # [0, 1, 2, 3, 4]
res = 0;
for item in list:
res += item
# 4950
res = 0
while len(list) > 0:
res += list[-1]
list.pop()
```
## 字典 (dicts)
```python
dicts = {'name': 'zxg' , 'sex': 'boy', 'age' : 18}
dict.pop('name'); # 刪除
dicts.get('name','default_value')
d = dict([('a', 1), ('b', 2), ('c', 3)])
d # {'a': 1, 'b': 2, 'c': 3}
# dict方法
```
## list和tuple
```python
s = ['python', 'java', ['asp', 'php'], 'scheme'] # list,list是有順序的,可以用來模擬隊列的FIFO特性
t = ('a', 'b', ['A', 'B']) # 成員不可變,但成員里面的長度可以變
t = (1,) # 因為tuple不可變,所以代碼更安全。如果可能,能用tuple代替list就盡量用tuple
list.append('Google')
del list['Google']
# http://www.runoob.com/python/python-lists.html
```
## 集合(set)
> 沒有value的dicts 無序集合,無重復
```python
s = set([1, 1, 2, 2, 3, 3]) # {1, 2, 3}
s.add(31)
s.remove(1)
s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
s3 = s1 & s2 # 交集 {2, 3}
s4 = s1 | s2 # 并集 {1, 2, 3, 4}
a = ['c', 'b', 'a']
a.sort()
a # ['a', 'b', 'c']
a = 'abc'
a.replace('a', 'A') # 'Abc'
a # 'abc'
```
## 數據類型判斷
> python是一切皆對象,判斷數據類型就是判斷其是否屬于某一個對象
### type
```python
type(123) # <class 'int'>
type('str') # <class 'str'>
type(None) # <type(None) 'NoneType'>
type(123)==type(456) # True
type('abc')==type(123) # false
type(Object) # <class 'type'> 自定義類(元類生成的)
```
### isinstance
```python
x = 2
s = 'ww'
isinstance(x, (int, float)) # True
isinstance(s, (int, float)) # False
```
### callable
判斷一個對象是否能被直接調用
```python
callable(Student()) # True
callable(max) # True
callable('str')
```
## 深拷貝和淺拷貝
```python
# 直接賦值,傳遞對象的引用而已,原始列表改變,被賦值的b也會做相同的改變
alist=[1,2,3,["a","b"]]
b=alist
alist.append(5)
print(b) # [1, 2, 3, ['a', 'b'], 5]
# copy淺拷貝,沒有拷貝子對象,所以原始數據改變,子對象會改變
import copy
c=copy.copy(alist)
alist.append(5)
print(c) # [1, 2, 3, ['a', 'b']] 最外層子對象沒有改變,因為此處不同于引用復制,而是淺拷貝
alist[3].append('cccc')
print(c) # [1, 2, 3, ['a', 'b', 'cccc']] 雖然外層對象沒改變,但里層的['a', 'b']已被改變
# 深拷貝,包含對象里面的自對象的拷貝,所以原始對象的改變不會造成深拷貝里任何子元素的改變
d=copy.deepcopy(alist)
alist[3].append("ccccc")
print(d) # [1, 2, 3, ['a', 'b'], 5] 里層外層都沒有被改變,因為d已經完完全全跟alist沒有關系了
```