Python 基本語句__Python

來源:互聯網
上載者:User
Python 基本語句

首先申明下,本文為筆者學習《Python學習手冊》的筆記,並加入筆者自己的理解和歸納總結。

1、Python語句特點 (1) if語句中括弧()是可選的。
(2) 冒號(:)出現在結尾,表示一個語句的結束。
(3) 分號(;)不用出現在結尾。
(4) 大括弧不在需要,而是以縮排來表示代碼塊的開始和結尾。

2、if語句 (1) 一般格式

if <state1>:               # if語句,以分號(:)結尾<statement1>           # 縮排替代大括弧elif <state2>:             # elif語句,可以有多個<statement2>else:                      # else語句<statement3>
(2) 只包含if語句。
>>> if x > 1:print "True"
(3) if和else配合使用。
>>> if x > 1:print "True"else:print "False"
(4) 多路選擇elif。
>>> if x < -1:print "x < -1"elif x < 0:print "x < 0"elif x < 1:print "x < 1"else:print "x >= 1"

3、while語句 (1) 一般格式。

while <state1>:            # where語句,以分號(:)結尾<statement1>else:                      # else語句,迴圈正常結束調用<statement2>
(2) while單獨使用。
>>> x = "HelloWorld!">>> while x:               # x是否是空列表print x[0],x = x[1:]H e l l o W o r l d !
(3) else是迴圈結束時調用。
>>> L = [1, 2, 3, 4]>>> while L:print L[0],L = L[1:]else:                      # 迴圈結束,調用else語句print 61 2 3 4 6

4、for語句 (1) 一般格式。

for <target> in <object>:  # for語句,以分號(:)結尾<statement1>else:                      # else語句,迴圈正常結束調用<statement2>
(2) for單獨使用。
>>> for x in [1, 2, 3, 4]:print x,1 2 3 4>>> for x in ("hello", "world"):print xhelloworld
for使用元組賦值。
>>> T = [(1, 2), (3, 4), (5, 6)]>>> for (a, b) in T:print a, b>>> for item in T:a, b = itemprint a, b1 23 45 6
for對字典操作時,實際是對字典的關鍵字列表操作。
>>> D = {"a":1, "b":2, "c":3}>>> for item in D:print item, D[item]a 1c 3b 2
(3) else是迴圈結束時調用。
>>> L = [1, 2, 3, 4]>>> for x in L:print x,else:print 61 2 3 4 6

5、break和continue語句用於迴圈語句中。 break用來跳出迴圈。

>>> x = "HelloWorld!">>> while True:if x:                  # x是否是空列表print x[0],x = x[1:]else:                  # x是空列表,跳出迴圈breakH e l l o W o r l d !
continue用來跳到迴圈的頂端。
>>> L = [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> for x in L:if x % 2 == 0:         # 如果x是偶數,跳過下面語句continueprint x,               # 該方法只會列印奇數1 3 5 7 9

6、pass語句

pass是空的佔位語句。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.