Python學習之路--03流程式控制制語句

來源:互聯網
上載者:User

標籤:ase   例子   流程   cas   img   縮排   基本   com   ssi   

目錄

  • 運算式
  • 流程式控制制語句
    • 條件控制語句
    • 迴圈控制語句
運算式

運算式(Expression)是運算子(operator)和運算元(operand)所構成的序列。是程式設計語言中最基本的概念之一

簡單地說python中的運算式就是一行行的語句

>>> 1+1112>>> a = [1,2,3]>>> 1+1+1*24>>> a = 1+2*3>>> a = 1>>> b = 2>>> c = a and b or 0>>> c = int(‘1‘) + 2

例子中的一行行輸入都被叫做運算式。說到運算式就不能不提運算式間的優先順序問題。Python不同類別運算子優先順序如所示。

注意:

  • ()的優先順序最高,可以使用()來驗證和修改執行順序
  • 同等級運算子中也存在優先順序問題。如邏輯運算子中not>and>or
  • 同級情況下執行順序是從左往右順序執行,也就是左結合。但當出現賦值=操作時會變成右結合,也就是不論是否=是當前第一優先順序,都要先將=右邊部分計算完成
>>> a or b and c1>>> not a or b + 2 == cFalse>>> (not a) or ((b + 2) == c)False>>> b = a is c
流程式控制制語句
  • 條件控制語句——選擇性問題
  • 迴圈控制語句——一種解決問題的基本思想
條件控制語句

if else語句。python中的使用方式為

if 邏輯判斷 :    deal with things    ...else :    deal with other things    ...

python規範碎碎念:

  • python預設每一行是一條語句,區別於c、java等必須以;結尾的方式,python中語句結尾處的;是可選的
  • python不依賴{}來識別代碼塊,而是依賴縮排對齊來標識代碼塊,也因此python代碼不能被壓縮和混淆。縮排要求是4空格為基準,使用時注意ide等工具中對tab鍵的步進量的設定

條件判斷最常應用的情境莫過於檢測使用者登入時的條件判斷了,下面簡單類比一下。input()是一個函數可以獲得使用者在控制台上的輸入,函數在後面單獨說

account = ‘Daniel Meng‘password = ‘123456‘print(‘please input account‘)user_account = input()print(‘please input password‘)user_password = input()if account == user_account and password == user_password :    print(‘success‘)else :    print(‘fail‘)
PS E:\Python> python .\c3.pyplease input accountmengplease input password123failPS E:\Python> python .\c3.pyplease input accountDaniel Mengplease input password123456success

python規範碎碎念:

  • python區分大小寫,var和VAR不同
  • python沒有常量機制,所有希望表示常量的變數應當全部用大寫表示,如ACCOUNT
  • python中變數的命名如果是組合詞的話通過_串連,區別於駝峰命名法等
  • python項目通常有很多個.py檔案組成,一個python檔案稱之為一個模組,每一個模組頂部都應有一個由``` ```包裹的部分,用於解釋當前模組的意義和作用
  • python中標識符前不要留空格
  • 每個python檔案都應留一個空行
  • 變數應置於函數或類中,直接暴露在模組中的變數一般理解為常量
  • 為了提高可閱讀性,多元運算子如=等左右應當各留空一格
‘‘‘    if-else條件陳述式的使用和規範‘‘‘ACCOUNT = ‘Daniel Meng‘PASSWORD = ‘123456‘print(‘please input account‘)USER_ACCOUNT = input()print(‘please input password‘)USER_PASSWORD = input()if ACCOUNT == USER_ACCOUNT and PASSWORD == USER_PASSWORD :    print(‘success‘)else :    print(‘fail‘)

控制語句可以獨立使用,也可以嵌套

if condition:    if expression:        passelse:    if condition:        pass    else:        passif expression:    passif expression:    pass

這裡講一下由縮排帶來的代碼塊的概念。對於同樣縮排水平的代碼屬於同一代碼塊,處於同一層級

# 代碼塊if expression:    code1        code11        code11            code22            code22                code33                code33    code2    code3else:    code1    code2    code3

當遇到多條件判斷時,可以使用elif文法,這是else if的簡寫。elseelif都不能單獨出現

a = input()a = int(a)if a == 1:    print(‘apple‘)elif a == 2:    print(‘orange‘)elif a == 3:    print(‘banana‘)else:    print(‘shopping‘)

注意,因為python是弱類型語言,所以input()函數統一都按字串類型捕獲,之後需要自行將資料轉換成自身希望的類型

python中沒有c,java中的switch case文法。python中可以使用上文所述的if... elif... elif... else形式來代替。進一步的官方建議也可以使用字典的形式來實現switch語句的作用

def function_1(...):    ...functions = {‘a‘: function_1,             ‘b‘: function_2,             ‘c‘: self.method_1, ...}func = functions[value]func()
迴圈控制語句

包括whilefor兩類迴圈。先說while迴圈

while condition:    #迴圈體    do your things    ...orther statements

迴圈語句很容易發生死迴圈的錯誤。在迴圈體中一定要有能影響迴圈條件的語句

counter = 0while counter <= 10:    # 代碼塊    counter += 1    print(‘I am While ‘ + str(counter))

python中無論是while還是for,都可以搭配else,表示迴圈條件結束後進行的操作

while condition:    do your things    ...else:    pass

pass指代的是空操作

while迴圈多用於遞迴,for迴圈多用於遍曆序列、集合或字典。也可以說while多用於迴圈次數不定,for用於迴圈次數確定的場合。

for target_list in expression_list:    do your things    ...

上面給出了for迴圈格式。其也可以搭配else操作

for target_list in expression_list:    passelse:    pass

迴圈控制語句可以嵌套使用

a = [[‘apple‘,‘orange‘,‘banana‘,‘grape‘],(1,2,3)]for x in a:    for y in x:        print(y,end=‘ ‘)else:    print(‘fruit is gone‘)
PS E:\Python\seven> python .\c2.pyapple orange banana grape 1 2 3 fruit is gone

else部分會在遍曆完,或者說for迴圈完成後執行。

小技巧 print()方法中可以使用第二個參數end,來控制結果輸出格式,預設end = ‘\n‘

在迴圈中往往有時對某些情況特殊處理,比如說臨界/錯誤時退出,忽略某些值等。這時就會使用到breakcontinue操作了

break會終止最內層迴圈,如果被終止層迴圈配有else部分,else部分也會被略過continue則是跳過當前第n次迴圈,直接進行第n+1次迴圈

a = [[‘apple‘,‘orange‘,‘banana‘,‘grape‘],(1,2,3)]for x in a:    for y in x:        if y == ‘banana‘:            break        elif y == 2:            continue        print(y)    else:        print(‘Done‘)
PS E:\Python\seven> python .\c2.pyappleorange13Done

注意例子中,因為break程式沒有輸出banana、grape和else部分。因為continue程式跳過了2,其餘部分正常輸出

如果有c、java等其他語言背景可能會產生疑問,上面的for更像是for each。如果是下面這種指定迴圈次數的經典for,python該怎麼表示呢?

for(int i = 0; i < n; i++){    do something}

對此,python使用了range(start,end[,step])函數,它可以接受三個參數,表示以步長step為單位擷取一個[start,end)範圍內的序列,步長可選,預設為1

for x in range(0,10):    print(x, end = ‘ | ‘)print()for x in range(0,10,2):    print(x, end = ‘ | ‘)print()for x in range(10,0,-2):    print(x, end = ‘ | ‘)
PS E:\Python\seven> python .\c3.py0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |0 | 2 | 4 | 6 | 8 |10 | 8 | 6 | 4 | 2 |

Python學習之路--03流程式控制制語句

聯繫我們

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