日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python新手菜鸟之基础篇

發(fā)布時間:2025/5/22 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python新手菜鸟之基础篇 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
s=0 for i in range(1,101):s += i else:print(s) def main(n):'''打印菱形圖形'''for i in range(n):print((' * '*i).center(n*3))for i in range(n,0,-1):print((' * '*i).center(n*3)) main(6) #計算理財產(chǎn)品收益 def licai(base,rate,days):result = basetimes = 365//daysfor i in range(times):result = result+result*rate/365*days #假設本金與利息一起滾動return result print(licai(100000,0.0543,90))#多次調(diào)用同一函數(shù)而產(chǎn)生的bug def demo(newiten,old_list=[]):'''如果增加一個判斷返回值初始化為默認值時,就不會產(chǎn)生bug如:if old_list is None: old_list=[]'''old_list.append(newiten)return old_list print(demo('5',['1','2','3'])) print(demo('aaa',['a','b'])) #在多次調(diào)用函數(shù)并不為默認值參數(shù)傳遞值時,默認值參數(shù)只 # 在第一次調(diào)用時進行解釋,這樣會導致bug print(demo('a')) print(demo('g'))#計算圓的面積 from math import pi as PI def CircleArea(r):if isinstance(r,(int,float)):return PI * r**2else:print('Error') print(CircleArea(3)) #使用lambda表達式,注意其變量的作用域 r=[] for x in range(10):r.append(lambda n=x:n**2)#不能直接引用x值,lambda表達式中使用局部變量 print(r[5]()) #類對象的定義 class A:def __init__(self,value1=0,value2=0):self._value1 = value1self.__value2 = value2def show(self):print(self._value1)print(self.__value2) a = A() print(a._value1) print(a._A__value2) #數(shù)據(jù)成員定義 class Demo(object):total = 0def __new__(cls, *args, **kwargs):#該方法在__init__()之前被調(diào)用if cls.total >= 3:raise Exception("最多只能創(chuàng)建3個對象")else:print('實例化',Demo.total)return object.__new__(cls)def __init__(self):Demo.total = Demo.total + 1 t1 = Demo() #方法 class Root:__total =0def __init__(self,v):self.___value=vRoot.__total +=1def show(self):print('Self:',self.___value)print('Root:',Root.__total)@classmethoddef classShowTotal(cls):'''類方法,只能訪問類成員'''print(cls.__total)@staticmethoddef staticShowTotal():'''靜態(tài)方法,也是只能訪問類成員'''print(Root.__total) r = Root(3) Root.classShowTotal() Root.staticShowTotal() r.show() #屬性 class Test1:def __init__(self,value):self.__value = value@property #修飾器屬性,只讀,無法修改和刪除def value(self):return self.__value class Test2:def __init__(self,value):self.__value = valuedef __getValue(self):return self.__valuedef __setValue(self,v):self.__value = vvalue = property(__getValue,__setValue)#設置屬性可讀可寫操作 #繼承 class Person:def __init__(self):print('this is a parent class')def setName(self,name):if not isinstance(name,str):print('name must be string.')self.__name = ''returnself.__name = nameprint(self.__name) #派生類 class Teacher(Person):def __init__(self):super(Teacher,self).__init__()#也可以直接用Persion.__init__()def setDepartment(self,department):#if type(department) != str:if not isinstance(department,str):print('department must be string.')self.__department = 'Computer'returnself.__department = department if __name__ == '__main__':zhangsan = Teacher()zhangsan.setName('Lisi') '''探討繼承中的問題,到底基類是否要繼承object呢''' class A:def foo(self):print('called A.foo()') class B(A):pass class C(A):def foo(self):print('called C.foo()') class D(B,C):pass d = D() d.foo()#A類繼承object,或不繼承object結果會是什么呢?(答案:called C.foo()) '''分析:如果A類是經(jīng)典類(不繼承object),當調(diào)用D的實例的foo()方法時,Python 會按照深度優(yōu)先的方法搜索foo(),路徑B-A-C,執(zhí)行A中的foo();如果A是新式類(繼承object), 則會按照廣度優(yōu)先的方法去搜索foo(),路徑B-C-A,執(zhí)行C中的foo();通過以上分析:其實新式類更符合邏輯;通常對應Python3.x中的新式類已經(jīng)兼容了經(jīng)典類,即無論A是否 繼承object類,D中都會執(zhí)行C中的foo()方法,但是在Python2.7-3.0中仍然存在上述的差異,所以我們推薦使用新 式類,要繼承object類''' #類的繼承機制 class A(object):def __init__(self):self.__private()self.public()def __private(self):#基類的私有成員方法print('__private Method of A1')def public(self):print('public Method of A2') class B(A):#沒有構造函數(shù),在創(chuàng)建實例時,直接走基類構造函數(shù),對于重寫# 非私有成員方法后,此時在基類調(diào)用的方法為派生類中的#如果有構造函數(shù),實例化時則直接是走派生類中的構造函數(shù)def __private(self):print('Method of B1')def public(self):print("public Method of B2") b = B() b.public()#字符串 #1.短字符串駐留機制,共享同一個副本值 a='1234' b='1234' print(id(a) == id(b),b) #2.格式化模板類 from string import Template t = Template('My name is ${name},and is ${age} years old') d ={'name':'dong','age':34} print(t.substitute(d)) #3.字符串常用方法find(),rfind(),index(),rindex(),count() '''find():查找字符串首次出現(xiàn)的位置rfind():查找字符串最后出現(xiàn)的位置index():查找字符串首次出現(xiàn)的位置''' s = 'apple,peach,banana,peach,pear' print(s.find('pp')) print(s.index('pp')) #4.split(),rsplit(),partition(),rpartition() '''split(),rsplit()返回的是列表,如果有多個連線空白字符在未指定分隔符情況下,默認作為一個partition(),rpartition()返回的是元組''' li = s.split(',') print(li) print(s.partition(',,'))#分隔成3部分,如果原字符串中不包含分隔符,則返回原字符串及兩個空字符串 ss='2014-10-20' print(list(map(int,ss.split('-'))))#map對數(shù)據(jù)進行類型轉換 #5.join()將列表中的多個字符串連接起來,并插入指定字符 lst = ['say','hello','miao','bai'] print("-".join(lst)) #使用split()與join()方法可以巧妙刪除字符串中多余的空字符,并保留一個 #6.lower(),upper(),capitalize(),title(),swapcase() '''lower():返回小寫字符串;upp():返回大寫字符串:capitalize():返回字符串首字符大寫;title():每個單詞首字母大寫;swapcase():大小寫互換;注意:這幾個方法都是返回新字符串,對原字符串不做任何修改''' #7.replace() 替換,也是返回新字符串 print('dfjgdifezadewwsaza'.replace('zad','ZAD')) #8.maketrans(),translate()方法生成字符映射表和按映射表轉換字符串并替換成字符,該方法可用來對字符串進行加密 #demo:創(chuàng)建映射表,將字符"abcdef123"一一對應轉換成'uvwxyz@#$' table =''.maketrans('abcdef123','uvwxyz@#$') s ='Python is a greate programming language,I like it!' print(s.translate(table))#按照映射表進行轉換,使用方法可以實現(xiàn)愷撒加密算法 #9.對不可變對象字符串進行修改,需使用io.StringIO或array模塊 #10.strip(),rstrip(),lstrip()分別用來刪除兩端、右端或左端連續(xù)的空字符串或指定字符串 '''這三個方法是對原字符串進行修改的''' print('aaasdffffsfafaaaa'.rstrip('a')) print('aaasdffaffsfafaaaa'.rstrip('af'))#注意:字符串中的af有不再兩側的,所以不刪除 #11.eval()對字符串轉換成Python表達式求值 print(eval('2+3')) print(eval('[2,3,4,5]'))#注意:這里不能使用list(x)進行轉換 #12.in、sartswith、endswith方法可用判斷是否存在或以指定字符串開始或結束 #demo:startswith、endswith可以接受一個元組,如判斷文件擴展名: import os [print(filename) for filename in os.listdir(r'F:\\') if filename.endswith(('.txt','.jpg','.gif'))] #13.center()、ljust()、rjust()、zfill()返回指定寬度的新字符串,原字符串居中、左對齊、右對齊、左側以字符0填充 print('hello world'.center(20,'-')) print('uoi'.zfill(20)) #13.切片--讀取字符串元素,不支持修改字符串 conent = 'Hello World!' print(conent[:7]) #案例精選 #1.編寫函數(shù)實現(xiàn)字符串加密和解密,循環(huán)使用指定密鑰,采用簡單的異或算法 def crypt(source,key):from itertools import cycleresult=''temp = cycle(key)for ch in source:result = result + chr(ord(ch)^ord(next(temp)))return result source ='ShangDong insitite of business and technology' key ='Dong Fuguo'print('Before source:'+source) encryt = crypt(source,key) print('After encryt:'+encryt) decryt = crypt(encryt,key) print('After decryt:'+decryt)

import itertools
'''chain:連接兩個列表進行迭代
?? count:從指定值開始,進入一個無界循環(huán)中
?? cycle:生成無界迭代器
?? filterfalse:返回一個可以使fun返回False的迭代器(python3.x中沒有ifilter)
?? islice:返回一個迭代器,并指定start開始,stop結束,step步長
?? zip_longest:返回迭代器,并將列表進行組合,生成元組
?? repeate:將對應列表按重復生成n次'''
listone=['a','b','c']
listtwo=['11','22','33']
# for item in itertools.chain(listone,listtwo):
#???? print(item)
# for item in itertools.count(10):
#???? print(item)
# for item in itertools.cycle(listone):
#???? print(item)#無線循環(huán)
def funLargeFive(x):
??? if x > 5:
??????? return True
# for item in itertools.filterfalse(funLargeFive,range(-10,10)):
#???? print(item)
listthree =[1,2,3]
def funAdd(x):
??? return x+5
for item in itertools.islice(listthree,1,2):
??? print(item)
for item in itertools.zip_longest(listone,listthree):
??? print(item)
stringBase='\u7684\u4e86\u662f'
print(''.join(stringBase.split('\\u')))
#目錄樹
import os
list_way = (list(os.walk(r".")))#產(chǎn)生一個三元tupple(dirpath[起始路徑],dirnames[起始路徑下的文件夾],filenames[起始路徑下的文件名])
# for root,dirs,files in os.walk(r'F:\UpSVNProject\DownSVNProject\YzDEC',True):
#???? print('root:%s'%root)
#???? print('dirs:%s' % dirs)
#???? print('files:%s' % files)
dict_way = dict( zip( [ i[0] for i in list_way] , list_way ) )
print(dict_way)
def to_txt(way):
??? l = [ ]
??? three = dict_way[ way ]
??? print("==",three)
??? tab_num = way.count("\\")
??? if tab_num:
??????? l.append("\t" * (tab_num - 1)+way.split("\\")[ -1 ] + "\n" )
??? for i in three[1]:
??????? l = l + to_txt( way+"\\"+i )
??? for i in three[2]:
??????? l.append( "\t" * tab_num + i +"\n")
??? return l
list_txt = to_txt(".")
print(list_txt)
with open("目錄樹.txt","w") as fil:
??? for i in list_txt:
??????? fil.write(i)
#os.system('notepad 目錄樹.txt')
#正則表達式
import re
text ='apleld.be3ate...ganem..dadein'
print(re.split('[\.]+',text,maxsplit=2))#匹配分隔符.一次或多次,maxsplit最多分隔兩次
print(re.findall('[a-zA-Z]+',text))#查找所有a-zA-Z的字符,以不是匹配的字符進行分隔
pat='name'
strs='Dear name..namelisty.'
print(re.sub(pat,'Mr.dong',strs))#匹配字符并替換指定的字符
example='shangdong institute of Business and technology is a very beautitful school'
print(re.findall('\\ba.+?\\b',example))#采用非貪婪模式
#使用re.compile()獲取正則表達式對象,然后在使用其方法
pattern = re.compile(r'\bi\w+\b')
print(pattern.findall(example))
example1='ControlVolumne[0]'
import random
print(re.sub('(?<=\\[).+?(?=])',str(random.choice(range(100))),example1))
#match對象
email='tony@tiremove_thisger.net'
m = re.search('remove_this',email)
print(email[:m.start()],email[m.end():],m.group(0))
#子模式擴展語法
mm = re.match(r'(?P<first_name>\w+) (?P<last_name>\w+)','Malcolm Reynolds')
print(mm.group('first_name'))#命名的子模式
print(mm.groupdict())
mmm = re.match('(\d+)\.(\d+)','24.1632')
print(mmm.groups())
# s= 'aabc adcd abbcd abccd abcdd'
# p = re.compile(r'(\b\w* (?P<f>\w+) (?P=f)\w*\b)')
# print(p.findall(s))
#案例精選
#1.提取字符串中的電話號碼
pattern = re.compile(r'(\d{3,4}-(\d{7,8}))')
print(pattern)
#json使用
import json
x=[1,31,4]
jx = json.dumps(x)
print(jx)#編碼
print(json.loads(jx))#解碼
#文件操作
'''需求:copy文件,并在新文件中行尾增加行號'''
filename =r'c:\Users\PGIDYSQ\Desktop\1111111e.gen'
with open(filename,'r') as fp:
??? lines = fp.readlines()??????????????????????????????? #讀取所有行
maxLength = max(map(len,lines))?????????????????????????? #最長行的長度

for index ,line in enumerate(lines):????????????????????? #遍歷所有行
??? newLine = line.rstrip()?????????????????????????? #清理行右側的空白字符
??? newLine = newLine + ' '*(maxLength + 5 - len(newLine))
??? newLine = newLine + "#" +str(index + 1) + '\n'????????? #添加行號
??? lines[index] = newLine

with open(filename[:filename.rfind('\\')+1] +'_new.gen','w') as fp:
??? fp.writelines(lines)
??? print(fp.name)

?

?

以上內(nèi)容由本人學習中所記錄的,有點亂,~~共勉

?

轉載于:https://www.cnblogs.com/ysq0908/p/9106099.html

總結

以上是生活随笔為你收集整理的python新手菜鸟之基础篇的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。