Python學習筆記(二)基礎文法

來源:互聯網
上載者:User
學習Python,基本文法不是特別難,有了C的基本知識,理解比較容易。本文的主要內容是Python基礎文法,學完後,能熟練使用就好。(開發環境依然是Python2.7,簡單使用)
一,基本知識
1,不需要預先定義資料類型(此說法值得商榷,姑且這麼說吧),這是與其他語言的最大不同(如C,C++,C#,Delphi等)

複製代碼 代碼如下:


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

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

複製代碼 代碼如下:


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

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

複製代碼 代碼如下:


1 >>> type(x)
2

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
>>> print y,type(y)
13.4

逗號運算子(,):可以實現連接字串和數字型資料。

複製代碼 代碼如下:


>>> 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,if分支語句:
1)形式一:(if :)

複製代碼 代碼如下:


>>> sex="male"
>>> if sex=='male':
print 'Man!'
#此處有兩次斷行符號鍵
Man!
>>>

2)形式二:(if : else (if :))

複製代碼 代碼如下:


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 : elif : 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!"

運行結果:

複製代碼 代碼如下:


1 >>>
2 Welcome you!
3 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!

五,小結:

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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.