[置頂]Python基本語法初試

編程環境:

win7旗艦版

Python 3.2.2(default, Sep  4 2011,09:51:08) 

代碼來源:(Python菜鳥)

代碼內容:

Python基本的輸出語句print("String");輸入語句input("Please enter what you want to say:")if else語法、while語法、for語句等嵌套語法。

Python語言中函數定義的方法:def function(arg1,arg2):  return S;。

Python的.py文件的調用方法import Myself_OutFlie以及文件中的函數的調用方法。

python基本的文件操作open(test.txt,'r+',100)函數、close()文件流關閉函數、write(b"test.txt",)寫操作函數、read("10")讀操作函數。

Python的類操作,類的繼承,類方法的重寫。

Python正則表達式的基本操作和簡單的文本處理。

Python和Mysql數據庫連接的方法API和基本的操作

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 import sys;
  4 import math;
  5 import time;
  6 import string;
  7 print('Hello World!');#打印字符串
  8 #print('愛你!');
  9 print(4+5,4*5,4/5,pow(4,5));
 10 #注意python的語法對文本縮進的格式要求很高,一定要保證
 11 if True:
 12     print ("Answer");
 13     print ("True");
 14 else:
 15     print ("Answer");
 16     print ("False");
 17 #total = item_one + \#連接符
 18     item_two + \
 19     item_three;
 20 print('total');
 21 days = ['Monday','Thuesday','Wednesday','Thursday','Friday'];
 22 print(days[0],days[1],days[2],days[3],days[4]);
 23 x = 'runoob';
 24 sys.stdout.write(x + '\n')
 25 counter = 100;#整形變量
 26 miles = 101.1;#浮點型數據
 27 name = 'mamiao';#字符型變量
 28 print(name,counter,miles);
 29 a,b,c =1,2,"mamiao";#相當於多個變量同時賦值
 30 print(a,b,c);
 31 del a,b,c;#刪除多個對象的引用
 32 real=3.001;
 33 image=4.002;
 34 Num_com=complex(real,image)
 35 Length=abs(Num_com);
 36 print("Complex Number is ",Num_com,".The Length is equal to",Length);
 37 str='I want to learn Python every well,but the time seem to be not enough!';
 38 print(str[1:10]);#截取字符串當中的一部分,小標的起始是從左到右,起始0-左
 39 print(str);#輸出完整字符串
 40 print(str[0]);#輸出字符串中的第一個字符
 41 print(str[2:5]);#輸出字符串中第三個至第五個之間的字符串
 42 print(str[2:]);#輸出從第三個字符開始的字符串
 43 print(str * 2);#輸出字符串兩次
 44 print(str + "TEST");#輸出連接的字符串
 45 #加號(+)是列表連接運算符,星號(*)是重複操作
 46 tuple = ('GPIO','FLASH','MCPU');#元組,不允許更新
 47 list = ['A','B','C'];#列表,可以更新
 48 A,B=10,11;
 49 B+=1;
 50 if (A>B) and (A==B):
 51     print('A is the big one');
 52 else: 
 53     print('B is the big one');
 54 print(A|B,A**B,A^B,~A,A<<2,A>>1);
 55 #Python成員運算符,in 運算符
 56 List = [1,2,3,4,5,10];
 57 if (A in List) and (B in List):
 58     print('Oh,yeal!');#一定要注意啊,目前加入不了utf8的庫,所以感嘆號一定是英文的感嘆號
 59 elif (A not in List) and (B not in List):
 60     print('Ok,There is no one of the Number!');
 61 else:
 62     print('Some number of them is in the List!');
 63 #Python語言中沒有 do while語句
 64 M=input("Enter your input:");
 65 print(M+'2');
 66 #數據類型轉換string--convert--int,eg:int('12')
 67 #數據類型轉換int--convert--string,eg:str('12')
 68 count=int(M);
 69 while (count < 10):
 70     print('The count number is equal to:',count);#注意縮進,縮進表示的是當前執行的代碼
 71     count+=1;
 72 print('Good bye!');
 73 i = 1
 74 while i < 10:   
 75     i += 1
 76     if i%2 > 0:     # 非雙數時跳過輸出
 77         continue
 78     print(i)         # 輸出雙數2、4、6、8、10
 79 
 80 i = 1
 81 while 1:            # 循環條件爲1必定成立
 82     print(i)         # 輸出1~10
 83     i += 1
 84     if i > 10:     # 當i大於10時跳出循環
 85         break
 86 #Python for循環可以遍歷任何序列的項目,如一個列表或者一個字符串
 87 for letter in 'Python':
 88     print('The letter is: ',letter);
 89 for day in days:
 90     print('Today is:',day);
 91 #通過序列索引迭代來完成對列表等字符串遍歷
 92 for index in range(len(days)):
 93     print(days[index]);
 94 #循環嵌套
 95 i = 2
 96 while(i < 100):
 97    j = 2
 98    while(j <= (i/j)):
 99       pass
100       #Python pass是空語句,是爲了保持程序結構的完整性。
101       #pass 不做任何事情,一般用做佔位語句
102       if not(i%j): break
103       j = j + 1
104    if (j > i/j) : print(i," prime num")
105    i = i + 1
106 print("Good bye!")
107 ticks = time.time()#獲取當前時間戳
108 print("The current time is:", ticks)
109 localtime = time.localtime(time.time())
110 print('The locate time is:',localtime)
111 localtime = time.asctime( time.localtime(time.time()))
112 print('The locate time is:',localtime)
113 
114 #python函數定義
115 def printme( str1,str2 ):#"打印傳入的字符串到標準顯示設備上"
116     print(str1+str2);
117     return;
118 printme('Hello world!','I Love Python!')
119 #兩種求和函數:
120 def sum1( arg1, arg2 ):
121    # 返回2個參數的和."
122    total = arg1 + arg2
123    print("kernel of function : ", total)
124    return total;
125 sum2 = lambda arg1,arg2:arg1+arg2;
126 print('The total is:',sum1(10,20));
127 print('The total is:',sum2(10,20));
128 content = dir(math)
129 print(content);
130 #調用自己編寫的外部庫函數,類似於C語言的.c文件source文件,注意調用的方式
131 import support;
132 support.print_func("Zara");
133 #from support import fibonacci#單獨引用support.py文件裏面的fibonacci函數,其餘函數都不調用
134 #from support import *#調用所有support文件裏面的函數模塊model
135 
136 a,b=0,10;
137 for a in range(b):
138     print(a);
139     a+=1;
140 
141 #import Python_Library;
142 #import fibonacci;
143 #fibonacci_func(10);#retry the function to run
144 
145 #file object = open("file_name","access","Buffer"]);
146 #filename是文件的名稱,access是object操作文件的權限,Buffer是文件是否以寄存器操作來運行
147 
148 #Buffer=1代表使用Buffer,當Buffer是大於1時,限制了Buffer的大小,Buffer=0表示不使用Buffer
149 #file對象的屬性
150 #file.closed    返回true如果文件已被關閉,否則返回false。
151 #file.mode    返回被打開文件的訪問模式。
152 #file.name    返回文件的名稱。
153 #file.softspace    如果用print輸出後,必須跟一個空格符,則返回false。否則返回true。
154 fo=open("test.txt","wb",1000);
155 print("The filename is :",fo.name);
156 print("The states of files :",fo.closed);
157 print("The Rquest_Model of files :",fo.mode);
158 print("Now time I will write something into the files named test.txt!");
159 fo.write(b'www.runoob.com!\nVery good site!\n');#傳遞測參數就是要寫入fo文件的內容,必須要#使
160 
161 用b參數來限定寫入的數據類型是byte類型
162 fo.close();
163 fo=open("test.txt","rb",1);
164 #file.read(count)函數傳遞的參數count是要從已打開文件中讀取的字節計數。該方法從文件的開頭
165 #開始讀入,如果沒有傳入count,它會嘗試儘可能多地讀取更多的內容,很可能是直到文件的末尾。
166 print("Now time I will read some information from the files named test.txt!");
167 Str1=fo.read();
168 print(Str1);
169 fo.close();
170 #tell()方法告訴你文件內的當前位置;換句話說,下一次的讀寫會發生在文件開頭這麼多字節之後
171 #seek(offset ,[from])方法改變當前文件的位置。Offset變量表示要移動的字節數。From變量指定#
172 
173 開始移動字節的參考位置,如果from被設爲0,這意味着將文件的開頭作爲移動字節的參考位置。如果#
174 
175 爲1,則使用當前的位置作爲參考位置。如果它被設爲2,那麼該文件的末尾將作爲參考位置
176 fo=open("test.txt","r+",1);
177 str=fo.read(10);
178 print(str);
179 position=fo.tell();
180 print("The position of file nowtime is equal to :",position);
181 position=fo.seek(0,0)
182 str=fo.read(10);
183 print(str);
184 fo.close();
185 
186 import os;
187 Path=os.getcwd()#獲得當前的路徑
188 print(Path)
189 os.mkdir("Subdirector");#當文件夾已經存在的時候不能再次創建它
190 os.rmdir("Subdirector");#刪除當前目錄下的文件夾
191 
192 class Employee:
193     'Hello,This the first class named Employee!'
194     empCount=0;
195     def __init__(self,name,salary):
196         self.name = name;
197         self.salary = salary;
198         Employee.empCount += 1;
199     def displayCount(self):
200         print("Total Employee %d"%Employee.empCount);#看這裏的語法,如何輸出變量
201     def displayEmployee(self):
202         print("Name:",self.name,",Salary:",self.salary);
203 emp1 = Employee("mamiao",20000);
204 emp2 = Employee("zhangle",30000);
205 emp3 = Employee("jujiabao",40000);
206 emp1.displayCount();
207 emp1.displayEmployee();
208 emp2.displayCount();
209 emp2.displayEmployee();
210 emp3.displayCount();
211 emp3.displayEmployee();
212 print("Total Employee %d"%Employee.empCount);#class申明的成員變量是共用的,public的
213 emp1.age = 7;#添加emp1的變量屬性age
214 emp1.sex = 1;
215 emp1.age = 8;#修改emp1的age變量值
216 print(emp1.age);
217 del emp1.age;#刪除emp1的變量屬性age
218 
219 #getattr(obj,'name',[default])#訪問對象的屬性。
220 #hasattr(obj,'name')#檢查是否存在一個屬性。
221 #setattr(obj,'name',value)#設置一個屬性。如果屬性不存在,會創建一個新屬性。
222 #delattr(obj,'name')#刪除屬性。
223 #getattr(emp1,'sex');
224 if hasattr(emp1,'sex'):
225     print("There is a member of emp1 named age!");
226 setattr(emp1,'Weight',60);
227 if hasattr(emp1,'Weight'):
228     print("There is a member of emp1 named Weight!");
229 delattr(emp1,'Weight');
230 if hasattr(emp1,'Weight'):
231     print("There is a member of emp1 named Weight!");
232 else:
233     print("The member has already been delete by User miaoma!");
234 print("Employee.__doc__:", Employee.__doc__)
235 print("Employee.__name__:", Employee.__name__)
236 print("Employee.__module__:", Employee.__module__)
237 print("Employee.__bases__:", Employee.__bases__)
238 print("Employee.__dict__:", Employee.__dict__)
239 
240 class Parent:#定義父類
241    parentAttr = 100
242    def __init__(self):
243       print("Callback the Structure-function of parent!");
244 
245    def parentMethod(self):
246       print('Callback the normal parent mothed!');
247 
248    def setAttr(self, attr):#成員變量更新方法setAttr
249       Parent.parentAttr = attr;
250 
251    def getAttr(self):
252       print("Characte-Value of Parent:", Parent.parentAttr);
253 
254    def Function_Overwrite(self):
255       print("This is Parent's Function!");
256 
257 class Child(Parent): # 定義子類,子類的內部調用了參數Parent,該參數表明Child類繼承了Parent類
258 
259 的基本方法
260    def __init__(self):
261       print("Callback Structure-function of Child!");
262 
263    def childMethod(self):
264       print('Callback child method');
265 
266    def Function_Overwrite(self):
267       print("This is Child's Function!");
268 
269 c = Child()          # 實例化子類
270 c.childMethod()      # 調用子類的方法
271 c.parentMethod()     # 調用父類方法
272 c.setAttr(200)       # 再次調用父類的方法
273 c.getAttr()          # 再次調用父類的方法
274 c.Function_Overwrite()    #方法重寫
275 
276 #__private_attrs:兩個下劃線開頭,聲明該屬性爲私有,不能在類地外部被使用或直接訪問。在類內
277 
278 部的方法中使用時 self.__private_attrs279 class JustCounter:
280     __secretCount = 0  # 私有變量
281     publicCount = 0    # 公開變量
282 
283     def count(self):
284         self.__secretCount += 1
285         self.publicCount += 1
286         print(self.__secretCount)
287 
288 counter = JustCounter()
289 counter.count()
290 counter.count()
291 print(counter.publicCount)
292 #print(counter.__secretCount)#報錯,實例不能訪問私有變量
293 
294 #Python正則表達式(提前學習正則表達式),需要引入頭文件:import re
295 #re.match 嘗試從字符串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回
296 
297 none
298 #函數語法:re.match(pattern, string, flags=0)
299 #pattern  匹配的正則表達式
300 #string     要匹配的字符串
301 #flags    標誌位,用於控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等
302 import re
303 print(re.match('www','www.runoob.com').span())  # 在起始位置匹配
304 print(re.match('com','www.runoob.com'))         # 不在起始位置匹配
305 
306 line = "Cats are smarter than dogs"
307 matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
308 if matchObj:
309    print("matchObj.group() : ", matchObj.group())
310    print("matchObj.group(1) : ", matchObj.group(1))
311    print("matchObj.group(2) : ", matchObj.group(2))
312 else:
313    print("No match!!")
314 #re.search 掃描整個字符串並返回第一個成功的匹配
315 #re.search(pattern, string, flags=0)
316 #pattern    匹配的正則表達式
317 #string    要匹配的字符串。
318 #flags    標誌位,用於控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等
319 #匹配成功re.search方法返回一個匹配的對象,否則返回None
320 print(re.search('www', 'www.runoob.com').span())  # 在起始位置匹配
321 print(re.search('com', 'www.runoob.com').span())         # 不在起始位置匹配
322 
323 searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
324 if searchObj:
325    print("searchObj.group() : ", searchObj.group())
326    print("searchObj.group(1) : ", searchObj.group(1))
327    print("searchObj.group(2) : ", searchObj.group(2))
328 else:
329    print("Nothing found!!")
330 
331 #比較match函數和search函數的區別,re.match只匹配字符串的開始,如果字符串開始不符合正則表達
332 
333 式,則匹配失敗,函數返回None;而re.search匹配整個字符串,直到找到一個匹配
334 matchObj = re.match( r'dogs', line, re.M|re.I)
335 if matchObj:
336    print("match --> matchObj.group() : ", matchObj.group())
337 else:
338    print("No match!!")
339 
340 matchObj = re.search( r'dogs', line, re.M|re.I)
341 if matchObj:
342    print("search --> matchObj.group() : ", matchObj.group())
343 else:
344    print("No match!!")
345 
346 #Python 的re模塊提供了re.sub用於替換字符串中的匹配項:re.sub(pattern, repl, string, max=0)
347 #返回的字符串是在字符串中用 RE 最左邊不重複的匹配來替換。如果模式沒有發現,字符將被沒有改變
348 
349 地返回。可選參數 count 是模式匹配後替換的最大次數;count 必須是非負整數。缺省值是 0 表示替
350 
351 換所有的匹配
352 phone = "2004-959-559 # This is Phone Number"
353 
354 # Delete Python-style comments
355 num = re.sub(r'#.*$', "", phone)
356 print("Phone Num : ", num)
357 
358 # Remove anything other than digits
359 num = re.sub(r'\D', "", phone)#\D匹配一個非數字字符,等價於等價於[^0-9]    
360 print("Phone Num : ", num)
361 
362 
363 #Python連接到數據庫必須學習,方便進行大數據的數據庫處理
364 
365 #Python2.6和Python3.0的版本的改變:
366 b = b'china';
367 print("b is :",b);
368 print("The type of b is:",type(b))
369 s = b.decode() 
370 print(s)
371 b1 = s.encode();
372 print("The type of b1 is:",type(b1))
373 print(b1)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章