Python學習系列(二)(基礎知識)


Python基礎語法

       Python學習系列(一)(基礎入門)

      對於任何一門語言的學習,學語法是最枯燥無味的,但又不得不學,基礎概念較繁瑣,本文將不多涉及概念解釋,用例子進行相關解析,適當與C語言對比,避免陷入語法的苦海。我認為初學者學習語法的目標是學會使用即可,關於對概念的深入理解,剖析,沒有一定的知識積累是很難做到的。

      學習Python,基本語法不是特別難,有了C的基本知識,理解比較容易。本文的主要內容是Python基礎語法,學完后,能熟練使用就好。(開發環境依然是Python2.7,簡單使用)

一,基本知識
1,不需要預先定義數據類型(此說法值得商榷,姑且這么說吧),這是與其他語言的最大不同(如C,C++,C#,Delphi等)
1 >>> x=12
2 >>> y=13
3 >>> z=x+y 4 >>> print z 5 25

注意:盡管變量不需要預先定義,但是要使用的時候,必須賦值,否則報錯:

1 >>> le 2 Traceback (most recent call last): 3   File "<pyshell#8>", line 1, in <module>
4  le 5 NameError: name 'le' is not defined

2,查看變量的類型函數type():

1 >>> type(x) 2 <type 'int'>
3,查看變量的內存地址函數id():
 1 >>> x=12
 2 >>> y=13
 3 >>> z=x+y  4 >>> m=12
 5 >>> print 'id(x)=',id(x)  6 id(x)= 30687684
 7 >>> print 'id(m)=',id(m)  8 id(m)= 30687684
 9 >>> print 'id(z)=',id(z) 10 id(z)= 30687528
11 >>> x=1.30
12 >>> print 'id(x)=',id(x) 13 id(x)= 43407128

從上述結果可以發現:變量的指向變,地址不變,換句話說,整數12的地址值始終不變,變化的是變量的指向(如x的地址變化);

4,輸出函數print()
1 >>> x='day'
2 >>> y=13.4
3 >>> print x,type(x) 4 day <type 'str'>
5 >>> print y,type(y) 6 13.4 <type 'float'>
逗號運算符():可以實現連接字符串和數字型數據。
1 >>> print 'x=',12
2 x= 12

格式化控制符:%f浮點數%s字符串;%d雙精度浮點數(這和C的輸出是一致的)。

1 >>> x=12
2 >>> y=13.0004
3 >>> z='Python'
4 >>> print "output %d %f %s"%(x,y,s) 5 output 12 13.000400 Python

5,輸入函數raw_input():

1 >>> raw_input("input an int:") 2 input an int:12
3 '12'
注意:raw_input()輸入的均是字符型。
6,查看幫助函數help():
1 >>> help(id) 2 Help on built-in function id in module __builtin__: 3  
4 id(...) 5     id(object) -> integer 6    
7     Return the identity of an object. This is guaranteed to be unique among 8     simultaneously existing objects. (Hint: it's the object's memory address.) 9  
注意:Python的注釋,#:僅支持單行注釋;另外,Python編程具有嚴格的縮進格式。
 
二、函數
1,函數定義及其調用:
 1 #define function:add (函數說明)
 2 def add(x,y):  #函數頭部,注意冒號,形參x,y
 3     z=x+y           #函數體
 4     return z        #返回值
 5 #define main function
 6 def main():  7     a=12
 8     b=13
 9     c=add(a,b)   #函數調用,實參a,b
10     print c 11 main()             #無參函數調用
12 print 'End1!'

注意:這部分與C的存在的異同在於:

1,形參與實參的用法,無參函數,有參函數,默認參數等規則一致。
如def add(x,y=2),調用可以是add(3)也可以是add(3,4),add(y=34,x)
2,C的形參需要指定數據類型,而Python不需要。
3,Python的返回值允許有多個。如:
 1 def test(n1,n2):  2     print n1,  3     print n2  4     n=n1+n2  5     m=n1*n2  6     p=n1-n2  7     e=n1**n2  8     return n,m,p,e  9 print 'Entry programme1'
10 sum,multi,plus,powl=test(2,10)   #這個是C語言所沒有的賦值方式
11 print 'sum=',sum 12 print 'multi=',multi 13 print 'plus=',plus 14 print 'powl=',powl 15 re=test(2,10) 16 print re                                #數據類型為:'tuple'
17 print re[0],re[1],re[2],re[3] 18 print 'End1!\n'

運行結果:

 1 Entry programme  2 2 10
 3 sum= 12
 4 multi= 20
 5 plus= -8
 6 powl= 1024
 7 2 10
 8 (12, 20, -8, 1024)  9 12 20 -8 1024
10 End!

2,局部變量:

 1 def f1():  2     x=12     #局部變量
 3     print x  4 def f2():  5     y=13      #局部變量
 6     print y  7 def f3():  8     print x       #錯誤:沒有定義變量x,這與“不需要預先定義數據類型”不矛盾
 9     print y 10 def main(): 11  f1() 12  f2() 13     #f3()#變量報錯 
14 main() 15 print 'End2!'
3,修改全局變量的值:
 1 def modifyGlobal():  2     global x              #全局變量定義
 3     print 'write x =-1'
 4     x=-1
 5 def main():  6 # printLocalx()
 7 # printLocaly()
 8 # readGlobal()
 9  modifyGlobal() 10  
11 x=200
12 #y=100
13 print 'before modified global x=', 14 print x 15 main() 16 print 'after modified global x=', 17 print x
運行結果:
1 >>>
2 before modified global x= 200
3 write x =-1
4 after modified global x= -1

三、表達式與分支語句

1,表達式:
      是由數字運算符,數字分組符號括號自由變量約束變量等以能求得數值的有意義排列方法所得的組合。表示通常有操作數和操作符兩部分組成。
      分類:算術表達式;關系表達式,邏輯表達式(and/or/not)
2,if分支語句:
1)形式一:(if <condition>:)
1 >>> sex="male"
2 >>> if sex=='male': 3  print 'Man!'
4 #此處有兩次回車鍵
5 Man! 6 >>> 

2)形式二:(if <condition>: else (if <condition>:))

1 sex=raw_input('Please input your sex:') 2 if sex=='m' or sex=='male': 3  print 'Man!'
4 else: 5     print 'Woman!'

運行結果:

1 >>>
2 Please input your sex:male 3 Man!

3)形式三:(if <condition>: elif <condition>: else ))(這是Python有而C沒有的形式)

 1 count=int(raw_input('Please input your score:'))  2 if count>=90:  3    print'優秀!'
 4 elif count>=80:  5     print '優良!'
 6 elif count>=70:  7     print '合格!'
 8 elif count>=60:  9     print '及格!'
10 else: 11     print '不及格!'

運行結果:

1 >>>
2 Please input your score:90
3 優秀!

注意:Python沒有switch語句。

 
四、循環語句
       背景:在程序設計的時候,經常會遇到一些語句被不斷的重復執行,這樣的代碼極長又低效,很不直觀,那么應該考慮用循環體來實現。
 1,while語句:與C在表達上有區別,c有while與do……while形式;Python下:while與while……else……形式
 1)while形式下:
1 i=1
2 while i<5: 3     print 'Welcome you!'
4     i=i+1

2)while……else……形式下:

1 i=1
2 while i<5: 3     print 'Welcome you!'
4     i=i+1
5 else: 6     print "While over!"  #循環正常結束

注意:如果while非正常狀態結束(即不按循環條件結束),則else語句不執行。如下:

1 i=1
2 while i<5: 3     print 'Welcome you!'
4     i=i+1
5     if i==2: 6         print 'While……'
7         break
8 else: 9     print "While over!"

運行結果:

1 >>>
2 Welcome you! 3 While……
補充:
continue語句:在while循環體中出現時,本次循環continue之下的語句不被執行,直接進入下一次循環。
 1 i=1
 2 while i<=5:  3     if i==2 or i==4:  4         print 'While……continue'
 5         i=i+1
 6         continue
 7     print 'Welcome you!'
 8     i=i+1
 9 else: 10     print "While over!"

運行結果:

1 >>>
2 Welcome you! 3 While……continue
4 Welcome you! 5 While……continue
6 Welcome you! 7 While over!

2,for語句:(見后續文章)

五,小結

      本文介紹了Python的變量,輸入輸出函數,表達式,基本語句(分支和循環)等知識的相關使用,通過練習,應該對Python有一個初步的認識。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM