1、print打印輸出
一、%形式輸出
1.1 print打印輸出
print("hello,world!")git
1.2 有如下格式符
%s 字符串 (採用str()的顯示)
%r 字符串 (採用repr()的顯示)
%c 單個字符
%b 二進制整數
%d 十進制整數
%i 十進制整數
%o 八進制整數
%x 十六進制整數
%e 指數 (基底寫爲e)
%E 指數 (基底寫爲E)
%f 浮點數
%F 浮點數,與上相同
%g 指數(e)或浮點數 (根據顯示長度)
%G 指數(E)或浮點數 (根據顯示長度)
%% 字符"%"api
2、邏輯優先級
邏輯優先級: not > and > or
print(True or False) # True
print(2 and 3) # 3
print(2 or 1 < 3) # 2
print(3 < 1 or 2 and 1) # 1
print(not 2 > 4 and 5 or 3 < 2 and 3) # 5閉包
3、字符類型
一、Integer
print(int(5.1)) # 5
print(int('5')) # 5
i = 5
print(i.bit_length()) # 3 Turn binary digits 101app
二、Strings
2.1 字符串經常使用函數
s = 'sA3 u43'
s0 = s.capitalize() # Sa3 u43
s1 = s.title() # Sa3 U43
s2 = s.replace('s','w') # wA3 u43
s31 = s.find('3',3,) # 6 find index,from 3 to end
s32 = s.find('3',3,6) # -1 last index
s33 = s.find('3') # 2 times
s4 = s.center(20,'*') # ******sA3 u43*******
s5 = s.count('3',1,4) # 1 count substr,index from 1 to 4
s6 = s.index('u',1,5) # 6
s7 = s.split() # ['sA3', 'u43'] change to list,default delimiter space
s8 = s.strip(3) # sA3 u4 Remove both sides matching characters,default space
s9 = s.startswith('u',4,) # True return Boolean type
s10 = s.endswith('2') # False
s11 = s.upper() # 'SA3 U43'
s12 = s.lower() # 'sa3 u43'
s13 = '#'.join(s) # s#A#3# #u#4#3dom
2.2 字符串切片
s = 'abcD1efs2'
s0 = s[:] # abcD1efs2
s1 = s[0:] # abcD1efs2
s2 = s[4:-1] # 1efs
s3 = s[4:-1:2] # 1f
s4 = s[4::-1] # 1Dcba
s5 = s[6:0:-2] # f1c
s6 = s[s.index('c'):0:-1] # cb
s7 = s[0:6:-2] # Noneide
三、List
3.1 列表增刪改查
li = ['alex','wusir']
3.1.1 增長列表
li.append('burton') # ['alex', 'wusir', 'burton']
li.insert(1,'lina') # ['alex', 'lina', 'wusir']
li.extend('boy') # ['alex', 'wusir', 'b', 'o', 'y']
3.1.2 刪除列表
name = li.pop(0)
print(name,li) # alex ['wusir'] 默認刪除最後一個
li.remove('alex') # ['wusir'] 按元素去刪除
li.clear() # 清空
del li # 刪除列內容和定義
del li[1:] # ['alex'] 切片去刪除
3.1.3 修改列表
li[0] = [1,'burton'] # [[1, 'burton'], 'wusir']
li[0:2] = [1,'burton','jm'] # [1, 'burton','jm']
3.1.4 查找列表
for i in li:
print(i) # alex wusir
print(li[0:2]) # ['alex', 'wusir']函數
3.2 公共方法
li = [1,5,6,2,5]
l = len(li) # 5
num = li.count(5) # 2
num = li.index(5) # 1
l1 = li.sort() # None 順序,只針對原列表
l2 = li.reverse() # None 倒序,只針對原列表
lst = ['alex','wusir']
s = '+'.join(lst) # 獲得字符串 alex+wusirspa
3.3 特殊列表
for i in range(2,5) # 2 3 4
for i in range(3) # 0 1 2
for i in range(0,10,3) # 0 3 6 9
for i in range(7,0,-2) # 7 5 3 1code
3.4 枚舉
list1 = [1,2,33]
for i, v in enumerate(list1):
print(i, ":", v)
result:
0 : 1
1 : 2
2 : 33遞歸
3.5 遍歷全部的元素
li = [1,2,3,5,'alex',[2,3,4,5,'taibai'],'afds']
for i in range(len(li)):
if type(li[i]) == list:
# if isinstance(li[i],list):
for j in li[i]:
print(j)
else:print(li[i])
3.6 去重複值:
def del_duplicates(values):
if len(values) == 0:
return False
lst = []
lst.append(values[0])
for i in range(1,len(values)):
if values[i] in lst:
continue
else:
lst.append(values[i])
return lst
print(del_duplicates([20,30,20,40,30]))
四、tuple(只讀列表,可循環查詢,可切片,兒子不能改,孫子可能能夠改)
tu = (1,'alex',[3,4,'taibai'])
tu[2][2] # taibai
tu[2][2]=tu[2][2].upper() # TAIBAI 轉成大寫
for i in tu:
print(i) # 查看元祖
五、Dictionary
dic1 = {'age': 18, 'name': 'jin'}
5.1 增長字典
dic1['height'] = 185 # 對沒有鍵值添加,有鍵值的覆蓋
dic1.setdefault('weight') # 沒有鍵值,默認爲None
dic1.setdefault('weight',150) # 位置隨機
dic1.setdefault('name','burton') # 有鍵值不添加
5.2 刪除字典
dic1.pop('age') # 18
dic1.pop('sex',None) # 沒key就會報錯,避免該問題可設置返回值
dic1.popitem()) # 隨機刪除 有返回值 元組裏面是刪除的鍵值。
del dic1['name'] # 刪字典內容,如沒對應key報錯
del dic1 # 刪整個字典
dic1.clear() #清空字典
5.3 修改字典
dic1['age'] = 16 # 原來有的key
dic2 = {"name":"alex","weight":75}
dic2.update(dic) # 原來有key修改,沒有增長
5.4 查找字典
print(dic1.items()) #打印出是個列表
for i in dic1.keys()
for i in dic1.values()
for k,v in dic1.items()
dic1.get('name1','no key') # 沒匹配就返回空,若有第二個參數,返回第二個參數
5.5 例子
def element_times(values):
if len(values) == 0:
return False
dic = {}
for i in range(0,len(values)):
if str(values[i]) in dic:
dic[str(values[i])] += 1
else:
dic[str((values[i]))] = 1
return dic
print(element_times([40,30,30,20,40,30,40]))
output result:
{'20': 1, '40': 3, '30': 3}
六、set
set1 = set({1,2,3})
set1 = {1,2,3} #元素是不可哈希
6.1 insert set content
set1.add('burton') # {1,2,3,'burton'}
set1.update('abc') # {1,2,3,'abc'}
6.2 delete set content
set1.pop() # 隨機刪除
print(set1.pop()) # 有返回值
set1.remove(2) # 按元素
set1.clear() # set()
del set1
6.3 intersection and union and so.
set1 = {2,3,4}
set2 = {4,5,6}
print(set1 & set2) # {4}
print(set1.intersection(set2)) # {4}
print(set1 | set2) # {2, 3, 4, 5, 6}
print(set2.union(set1)) # {2, 3, 4, 5, 6}
print(set1 ^ set2) # {2, 3, 5, 6}
print(set1.symmetric_difference(set2)) # {2, 3, 5, 6}
print(set1 - set2) # {2, 3}
4、Files
一、read file
The testfile.txt file is stored in 'abc'
e.g.1 # 'r' read mode
f = open('testfile.txt',mode='r',encoding='utf-8')
content = f.read()
print(content)
f.close()
# must close the file after used
result: abc
with open('testfile.txt',mode='r',encoding='utf-8') as f:
print(f.read()) # needn't close the file
output result: abc
e.g.2 # 'r+b' read mode
f = open('testfile.txt',mode='r+b')
content = f.read()
f.close()
print(content)
output result: b'abc'
e.g.3 # '你好' in file
f = open('testfile.txt',mode='r+b')
print(f.read())
f.write('大猛'.encode('utf-8'))
f.close()
output result: print b'\xe4\xbd\xa0\xe5\xa5\xbd' ,'你好大猛' in file
e.g.4 # 'r+' read mode,'abc' in file
f = open('testfile.txt',mode='r+',encoding='utf-8')
content = f.read()
print(content)
f.write('ABC')
f.close()
output result: print 'abc' , 'abcABC' in file
e.g.5 # We change the order of reading and writing,'abc' in file
f = open('testfile.txt',mode='r+',encoding='utf-8')
f.write('ABC')
content = f.read()
print(content)
f.close()
output result: print None , 'ABC' in file
二、write file
e.g.1 # 'abc' in file
f = open('testfile.txt',mode='r',encoding='utf-8')
f.write('DBA')
f.close()
result:'DBA' # The file content will be recover by 'DBA'
e.g.2 # 'abc' in file
f = open('testfile.txt',mode='w+',encoding='utf-8')
f.write('aaa')
f.seek(0)
print(f.read())
f.close()
result:print 'aaa','aaa' in file
e.g.3 # 'wb'mode
f = open('testfile.txt',mode='wb')
f.write('佳琪'.encode('utf-8'))
f.close()
result:'佳琪' in file
e.g.4 # 'abc' in file
f = open('testfile.txt',mode='a+',encoding='utf-8')
f.write('佳琪')
f.seek(0) #move cursor position
print(f.read())
f.close()
output result:print 'abc佳琪',also 'abc佳琪' in file
三、Other function
print(f.tell()) # tell you where is cursor position
f.truncate(4)
f.readlines() # Read files line by line
四、 Give some examples
e.g.1
# 'abc\nABC' in file
with open('testfile.txt',mode='r',encoding='utf-8') as f:
for i in f.readlines()
print(i)
outputresult:
abc
ABC
5、FUNCTION
一、Description function
def func():
'''
You can describe what function is implemented.
How to use parameter values
what return
'''
pass
二、How to use function
e.g.1
def sum(a,b=2,*args):
total = a +b
for i in args:
total += i
return total
print(sum(1,4,9,10)) #24
print(sum(2)) #4
e.g.2
def func1(a,b=1,**kvargs):
print(a,b,kvargs)
func1(3,4,x=4,y=5) # 3 4 {'x': 4, 'y': 5}
e.g.3
def func2(*args,**kvargs):
print(args,kvargs)
func2('a',1,x=3,y=2) # ('a', 1) {'y': 2, 'x': 3}
e.g.4
def func3(a,*args):
total = a
for i in args:
total += i
return total
li = [1,3,5,7,9]
print(func3(*li)) # 25
三、遞歸函數
e.g.5 #斐波那契數列 1,1,2,3,5,8,13,21,34,55
#mothed 1
def fun(n):
if n == 1:
return 1
if n == 2:
return 1
return fun(n-1) +fun(n-2)
print(fun(6)) # 8 這樣寫效率不好
#mothed 2
def fib(n,a=1,b=1):
if n==1 : return a
return fib(n-1,b,a+b)
print(fib(6)) # 8 這樣寫效率高
四、變量做用域
e.g.6 # nolocal 通常是用在閉包函數裏
x = 123
def outer():
x = 100
def inter():
nonlocal x
x = 200
inter()
print(x)
outer()
output result: 200
e.g.7 # global全局變量
x = 123
def testglobal():
global x
print(x)
x = 100
print(x)
testGlobal()
print(x)
output result:
123
100
100
五、Give some examples
e.g.8 # 登入驗證
my_script1.py
def judgment(user,li=[]):
for i in range(len(li)):
if user in li[i].keys():
return 1
if not user.isalnum() and user[0].isdigit():
return 2
return 3
def register(user,pswd,li=[]):
li.append({user:pswd})
return li
li = [{'lina': '342'}, {'burton': '223'}]
flag = True
i = 0
while i < 3:
usernm = input("Please enter username:")
if judgment(usernm,li) == 1:
print('該帳號已被註冊,請從新輸入帳號。')
i += 1
continue
elif judgment(usernm,li) == 2:
print('輸入的帳號只能數字和字母,且不能數字開頭!')
i += 1
continue
else:
passwd = input("Please enter password:")
register(usernm,passwd,li)
break
else:
print('你沒有機會了!')
print(li)
e.g.9 # 隨機數據和字母驗證碼# def ger_verif(arg):# l=[]# for i in range(48,58):# l.append(chr(i))# for i in range(65,91):# l.append(chr(i))# for i in range(97,123):# l.append(chr(i))# lst = random.sample(l,arg)# print(''.join(lst))# return ''.join(lst)def ger_verif(arg): s="" for i in range(0,arg): cur = random.randint(0,5) if cur > 2: cur = chr(random.randint(65,90)) elif i < 2: cur = chr(random.randint(97,122)) else: cur = chr(random.randint(48,57)) s += cur print(s) return sdef verification(): num = 3 gere = ger_verif(6) while num > 0: str = input('Please enter code:') if len(str) == 0: return 0 if gere.upper() != str.upper(): num -= 1 print('Please enter correctly verification!') else: return 1 return 0ret = verification()print(ret)