1,避免‘\n’等特殊字符的兩種方式:
1,利用轉義字符‘\’
2,利用原始字符‘r’ print r'c:\now'
3,字符串中嵌入雙引號等特殊符號
1,利用轉義字符‘\’
2,使用單引號括起這個字符串 print ('i l"o"ve fis.com')
2,跨越多行的字符串。使用三個'''........'''
4,條件分支:
if condition:
條件爲真執行的操作
else:
條件爲假執行的操作
if condition:
action
elif condition:
action
else:
action
python可以有效避免“懸掛else”(if else對應關係出錯)
條件表達式(三元操作符)
small = x if x<y else y
如果x<y ,small=x.否則small=y
斷言assert:當這個關鍵字後面的條件爲假,程序自動崩潰並拋出異常
assert 3>4
可以利用他置入檢查點
5,while條件:
條件爲真執行的操作
for 目標 in 表達式:
循環體
例:favorite='fishc'
for i in favorite:
print(i,end='')
range([start,] stop[,step=1])
生成一個從start參數的值到stop參數值的數字序列
break:終止當前循環體。跳到外層程序
continue:終止本輪循環,開始下一輪循環(if condition true)
6,and邏輯操作符可以將任意表達式連接在一起,並得到一個布爾類型值
7,引入外援:
1,random模塊
2,randint(),返回一個隨機的整數
import random 或 from random import randint()
secret=random.randint(1,10)
8,python數據類型
1,數值類型:整型、布爾類型、浮點型、e記法(1.5e10)
2,類型轉換:
int()轉換爲整數
str()轉換爲字符串
float()轉換爲浮點數
3,獲取關於類型的信息:
type()函數
a=520
type(a)
isinstance()函數
a=12
isinstance(a,int) --->返回true
isinstance(a,str) -->返回false
9,Python值常用操作符
+ - * / % **(冪運算) //(地板除法,結果偏小)
比較操作符 > < >= <=
邏輯操作符 and or not
優先級:
冪運算**
正負號 + -
算術操作符 * / //
+ -
比較操作符 < > =
邏輯擦作福 not and or
10,列表-->可以把整數、浮點數、字符串等打包在一起。數組卻不能
創建一個普通列表:
member = ['小甲魚','小布丁','黑夜']
創建一個混合列表:
mix=[1,'小甲魚',3.12,[1,2,3]]
創建空列表:
empty=[]
向列表添加元素:
append(): member.append('福祿娃')-->只能添加一個。末尾
添加
extend(): member.extend(['test','test1'])-->只能以列表
形式添加.末尾添加
insert(): member.insert(1,'牡丹')-->第一位插入牡丹
列表中獲取元素: 使用索引index。 mix[1]
列表中刪除元素: 使用remove()。 mix.remove('小甲魚')
使用del。 del mix[3]/mix
使用pop(). mix.pop()/mix.pop(1)
列表切片: 使用slice。 mix[1:4]/mix[1:]/mix[:4]
列表操作符: >,and,+,*,in/not in
列表的小夥伴: dir(list)
mix.count('小甲魚')
mix.index('小甲魚')
列表逆序: 使用reverse。 mix.reverse()
列表排序: 使用sort。 mix.sort()
mix.sort(func,key)
mix.sort(reverse=True)
11,元組--->不可改變的列表
和列表的主要不同點:
1,創建和訪問一個元組: 大部分用()/, ;列表用[]
2,元組不可修改數值
3,更新和刪除一個元組:temp = temp[:2] + ('test3',) + temp[2:]
del temp
4,IN/NOT IN,關係操作符,邏輯操作符,乘號操作符,連接操作符
12,字符串的各種內置方法
str1='i love fishc.com'
a=str1[:6] + '插入的字符串'+str1[6:]
capitalize(): str2.capitalize()
casefold()--->全部小寫 str2.casefold()
center(width)-->居中,不足空格填充
count(sub[,start[,end]])-->返回sub在string中出現的次數
endswith(sub[,start[,end]])-->以sub結束?
startswith(prefix[,start[,end]])-->以prefix開頭
expandtabs([tabsize=8])-->將tab鍵轉換爲空格
find(sub[,start[,end]])-->sub是否在字符串中出現
rfind(sub)...
index(sub[,start[,end]])-->跟sub一樣,不過會產生異常
rindex(sub..).....
istitle()/isupper()/ljust(width)/lower()/strip()/title()/lower()
join(sub):以字符串做分隔符,分割sub
partion(sub):找到子字符串sub,把字符串分成一個3元組
replace(old,new[,count])
split(sep=none,maxsplit=-1)-->不帶參數以空格做分隔符
swapcase()-->字符串大小寫翻轉
zfill(width)-->返回長度爲width的字符串,不夠補充空格
13,字符串格式化 replacement
"{0} love {1}.{2:.2f}".format("i","fishc",3.1424)
"{a} love {b}.{c}".format(a="i",b="fishc",c="com")
"{0} love {b}.{c}".format("i",b="fishc",c="com")
格式化符號含義
%c:格式化字符及其ASCII碼
'%c %c %c' % (97,98,99)
%s:格式化字符串
%d:格式化整數
%o:格式化無符號八進制數
%x:格式化無符號十六進制數 %X:...(大寫)
%f:格式化定點數,可指定小數點後的精度
%e:用科學技術發格式化定點數===%E
%g:根據值的大小決定使用%f或%e===%G
格式化操作符輔助命令
m.n :m是顯示的最小總寬度,n是小數位精度
- :用於左對齊
+ :在正數面前添加正號
# :在八進制面前顯示0,在十六進制面前顯示0x
0 :空格用0填充
字符串轉義字符
\a:發出系統響鈴聲
\b、\t、\n
.....
14,序列
列表、元組和字符串的共同點:
都可以通過索引
索引值從零開始
內置方法:
list() ——>help-->轉換爲序列
list()
a=list()
list(iterable)
b='i love fishc.com'
b=list(b)
tuple([iterable])-->把一個可迭代對象轉換爲元組
b=tuple(b)
str(obj)-->把obj對象轉換爲字符串
len(obj)-->返回obj的長度
max(序列/元組) / min(序列/元組)
sum(iterable[,start=0])-->返回序列iterable。。的總和
sorted(序列/元組)-->排序
reversed(序列/元組)-->返回一個迭代器對象
list(reversed(序列/元組))-->返回序列
enumerate(序列/元組)-->返回一個迭代器對象
list(enumerate(序列/元組))-->返回數組形式列表
zip(a,b)-->合併成以元組形式的列表
list(zip(a,b))
15,函數
定義:def Myfunction():
print('this is my first function')
調用:Myfunction()
函數的參數:
def Myfunction(name,age):
print(name+age+'test')
Myfunction('gncao',‘age’)
函數的返回值:
return value
形參(parameter):函數定義時的參數
實參(argument):實際傳遞的參數
函數文檔:在函數中實現
在函數體中用 '' 或 #
查看函數文檔: 1, functionname.__doc__ (四個下劃線)
2, help(functionname)
關鍵字參數:避免參數出亂
def Myfunction(words,name):
...
Myfunction(words='words123',name='name123')
默認參數:
def Myfunction(name='name123',words='words123')
...
收集參數:在參數前面加上*號
def test(*params):
print('參數的長度是:',len(params))
print('第二個參數是:',params[1])
test(1,'小甲魚',2,4,5,6,7)
def test(*params,exp):
print('參數的長度是:',len(params),exp)
print('第二個參數是:',params[1])
test(1,'小甲魚',23,4,2,5,7,exp=0)
16,函數有返回值,過程沒有返回值
17,函數變量作用域(可見性)
局部:local-->函數內部定義的變量,局部可用
全局:global-->全局可訪問
當在函數內部試圖修改全局變量時,則會在函數內部新建一個跟
全局變量名相同的局部變量
18,內嵌函數和閉包
global關鍵字:
def myfun():
global count ->>>全局變量
count=10
print(count)
內嵌函數:
def fun1():
print('fun1()正在被調用...')
def fun2():
print('fun2()正在被調用')
fun2()
只能通過fun1()訪問fun2()
閉包:在一個內部函數中,對外部函數的變量的引用。成內部函數爲閉包
def funx(x):
def funy(y):
return x * y
return funy
調用方式:
i=funx(8)
i(5)
或
funx(4)(5)
通過關鍵字nonlocal可以使得內部函數調用外部函數變量。
def fun1():
x=5
def fun2():
nonlocal x
x*=x
return x
return fun2()
19,遞歸:recursion()
def fac(n):
if n==1:
return 1
else:
return n*fac(n-1)
number=int(input('請輸入一個整數:'))
result=fac(number)
print('%d 的階乘是:%d' % (number,result))
迭代方法:
def fab(n):
n1=1
n2=1
n3=1
if n <1:
print('輸入有錯')
return -1
while ( n-2>0 ):
n3=n2+n1
n1=n2
n2=n3
n-=1
return n3
result=fab(20)
if result != -1:
print('總共有%d對小兔子誕生:' % result)
遞歸方法:
def fab(n):
if n < 1:
print('error')
return -1
if n==1 or n==2:
return 1
else:
return fab(n-1) + fab(n-2)
result=fab(20)
print('總共有%d對兔子誕生' % result)
但是遞歸的效率比較低
20,字典(key-value)
映射/序列
例1:
dict1={'李寧':'一切皆有可能','耐克':'just do it','阿迪達斯':'impossible
is nothing'}
print('李寧的口號是:',dict1['李寧'])
例2:
dict3=dict((('f',70),('i',105)))
例3:
dict4=dict(小甲魚='編程改變世界',test='test')
dict4['小甲魚']='修改小甲魚對應的value' -->如果沒有該KEY,則會自動添
加一個KEY
字典的內建方法:
0,dict2['key']-->訪問字典的元素
1,fromkeys(s[,v]) -->創建或查詢key
dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
dict1.fromkeys((1,2,3),'number')
{1: 'number', 2: 'number', 3: 'number'}
2,
keys()-->dict.keys() -->打印出dict的所有key
values()-->dict.values() -->打印出dict的所有value
items()-->dict.items() -->打印出dict所有(key,value)
get()--> dict.get(key) -->打印key對應的value
dict.get(key,'text')-->打印key對應的value,如果不存在,則打印
text
in操作符 --> key in dict2
clear() -->dict.clear() -->清空dict的數據
copy() -->b=a.copy() -->拷貝字典
id(a)-->查看id
pop(key) --> dict.pop(key) -->彈出key
popitem() -->dict.popitem() -->隨機彈出key
setdefault() -->dict.setdefault(key) -->新建key
update() -->dict.update(dict) -->更新字典
21,集合 --->唯一性
num={1,2,3,4,5}
set()-->set1=set(列表/元組/字符串)
不支持索引
訪問集合中的值:
使用for循環一一查找
使用IN 或者 NOT IN
add()-->set1.add(value)
remove()-->set1.remove(value)
不可變集合:
num3=frozenset(元組/列表)
22,文件
輸入-->處理-->輸出
內存--->磁盤
open()打開文件:
open('filename/path',mode='rwxabt+U')
文件對象方法:
f.close() -->關閉文件
f.read(size=-1) -->從文件讀取size個字符
f.readline() -->以寫入模式打開,如果文件存在,則在末尾添加
f.write(str) -->將str寫入文件
f.writelines(seq) ->向文件寫入seq序列。seq應該是一個返回字符串序列
f.tell() -->返回當前的位置。書籤
f.seek(offset,from) -->在文件中移動文件指針,從from偏移offset字節
for each in f: ---->瀏覽整個文件
print(each)