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

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

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

一,基本知識

1,不需要預先定義數據類型(此說法值得商榷,姑且這麼說吧),這是與其他語言的最大不同(如C,C++,C#,Delphi等)

>>> x=12
>>> y=13
>>> z=x+y
>>> print z

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

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

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

>>> type(x)
<type 'int'>

3,查看變量的內存地址函數id():

>>> x=12
>>> y=13
>>> z=x+y
>>> m=12
>>> print 'id(x)=',id(x)
id(x)= 30687684
>>> print 'id(m)=',id(m)
id(m)= 30687684
>>> print 'id(z)=',id(z)
id(z)= 30687528
>>> x=1.30
>>> print 'id(x)=',id(x)
id(x)= 43407128

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

4,輸出函數print()

>>> x='day'
>>> y=13.4
>>> print x,type(x)
day <type 'str'>
>>> print y,type(y)
13.4 <type 'float'>

逗號運算符():可以實現連接字符串和數字型數據。

>>> print 'x=',12
x= 12

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

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

5,輸入函數raw_input():

>>> raw_input("input an int:")
input an int:12
'12'

    注意:raw_input()輸入的均是字符型。

6,查看幫助函數help():

>>> help(id)
Help on built-in function id in module __builtin__:
id(...)
    id(object) -> integer
   
    Return the identity of an object. This is guaranteed to be unique among
    simultaneously existing objects. (Hint: it's the object's memory address.)

    注意:Python的註釋,#:僅支持單行註釋;另外,Python編程具有嚴格的縮進格式。

 

二、函數

1,函數定義及其調用:

#define function:add (函數說明)
def add(x,y):  #函數頭部,注意冒號,形參x,y
    z=x+y           #函數體
    return z        #返回值
#define main function
def main():
    a=12
    b=13
    c=add(a,b)   #函數調用,實參a,b
    print c
main()             #無參函數調用
print 'End1!'

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

           1,形參與實參的用法,無參函數,有參函數,默認參數等規則一致。

              如def add(x,y=2),調用可以是add(3)也可以是add(3,4),add(y=34,x)

           2,C的形參需要指定數據類型,而Python不需要。

           3,Python的返回值允許有多個。如:

def test(n1,n2):
    print n1,
    print n2
    n=n1+n2
    m=n1*n2
    p=n1-n2
    e=n1**n2
    return n,m,p,e
print 'Entry programme1'
sum,multi,plus,powl=test(2,10)   #這個是C語言所沒有的賦值方式
print 'sum=',sum
print 'multi=',multi
print 'plus=',plus
print 'powl=',powl
re=test(2,10)
print re                                #數據類型爲:'tuple'
print re[0],re[1],re[2],re[3]
print 'End1!\n'

運行結果:

Entry programme
2 10
sum= 12
multi= 20
plus= -8
powl= 1024
2 10
(12, 20, -8, 1024)
12 20 -8 1024
End!

2,局部變量:

def f1():
    x=12     #局部變量
    print x
def f2():
    y=13      #局部變量
    print y
def f3():
    print x       #錯誤:沒有定義變量x,這與“不需要預先定義數據類型”不矛盾
    print y
def main():
    f1()
    f2()
    #f3()#變量報錯  
main()
print 'End2!'

3,修改全局變量的值:

def modifyGlobal():
    global x              #全局變量定義
    print 'write x =-1'
    x=-1
def main():
# printLocalx()
# printLocaly()
# readGlobal()
    modifyGlobal()
 
x=200
#y=100
print 'before modified global x=',
print x
main()
print 'after modified global x=',
print x

運行結果:

>>>
before modified global x= 200
write x =-1
after modified global x= -1


三、表達式與分支語句

1,表達式:

    是由數字運算符,數字分組符號括號自由變量約束變量等以能求得數值的有意義排列方法所得的組合。表示通常有操作數和操作符兩部分組成。

      分類:算術表達式;關係表達式,邏輯表達式(and/or/not)

2,分支語句:

1)形式一:(if <condition>:)

>>> sex="male"
>>> if sex=='male':
 print 'Man!'
#此處有兩次回車鍵(python2.7環境)
Man!

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

sex=raw_input('Please input your sex:')
if sex=='m' or sex=='male':
 print 'Man!'
else:
    print 'Woman!'

運行結果:

>>>
Please input your sex:male
Man!

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

count=int(raw_input('Please input your score:'))
if count>=90:
   print'優秀!'
elif count>=80:
    print '優良!'
elif count>=70:
    print '合格!'
elif count>=60:
    print '及格!'
else:
    print '不及格!'

運行結果:

>>>
Please input your score:90
優秀!

   注意:Python沒有switch語句。

 

四、循環語句:

       背景:在程序設計的時候,經常會遇到一些語句被不斷的重複執行,這樣的代碼極長又低效,很不直觀,那麼應該考慮用循環體來實現。

1,while語句:與C在表達上有區別,c有while與do……while形式;Python下:while與while……else……形式

1)while形式下:

i=1
while i<5:
    print 'Welcome you!'
    i=i+1

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

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

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

i=1
while i<5:
    print 'Welcome you!'
    i=i+1
    if i==2:
        print 'While……'
        break
else:
    print "While over!"

運行結果:

>>>
Welcome you!
While……

補充:

continue語句:在while循環體中出現時,本次循環continue之下的語句不被執行,直接進入下一次循環。

i=1
while i<=5:
    if i==2 or i==4:
        print 'While……continue'
        i=i+1
        continue
    print 'Welcome you!'
    i=i+1
else:
    print "While over!"

運行結果:

>>>
Welcome you!
While……continue
Welcome you!
While……continue
Welcome you!
While over!

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


五,小結:

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


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