跳到主要內容


Python-迴圈

Python

迴圈概念說明:

基本語法:

while範例

while True:
     command = input('Your command : ')
     if command == 'q':
          break
     else:
         print(command)

程式碼說明

在while 後面加上條件式,範例是直接加一個true,此時while判斷為true時,迴圈不會停止,在while行結束時要加上:,下一行開始要縮排,表示在while迴圈內部,範例程式是,等待輸入,判斷輸入為q則離開,不為q則print出來。

for範例

for i in range(10):
    print(i)

for i in [1,3,5,6]:
    print(i)

a = [1,3,5,6]
for i in a:
    print(i)


程式碼說明

range(10) = [0,1,2,3,4,5,6,7,8,9]
i 定義變數
in 指定i 為in後面的可迭代物件的內容,並依可迭代物件順序,賦予i值
for 根據後方可迭代物件的長度決定執行次數,結尾時要加上:,下一行開始要縮排,其縮排內容皆為for迴圈內容

 投影片-slideshare:Python_迴圈
 影片-youtube:Python_迴圈
 程式碼-Github:Python_迴圈
下一單元:Python-函數

留言

這個網誌中的熱門文章

程式語言學習概論(1)

程式語言 介紹

Python-設計模式-共享模式

Python 設計模式 共享模式 class Font:     def __init__(self):        self.Size = 0        self.Type = ''     def printAll(self):        print(self.Size, self.Type)  class FontFacotry:     def Word(self, Size=3, Type='1'):        F = Font()        F.Size = Size        F.Type = Type        return F  FontSize = [1,2,3] FontType = ['1','2','3'] Facotry = FontFacotry()  F1 = Facotry.Word(FontSize[0],FontType[0])  F1.printAll()  F2 = Facotry.Word( FontSize[1],FontType[1] ) F2.printAll()  F3 = Facotry.Word( FontSize[2],FontType[2] ) F3.printAll() 程式碼說明 font 定義類別 fontFacotry物件生成工廠 fontsize用來儲存font大小的外部空間 fonttype用來儲存font種類的外部空間

Python-設計模式-建造者模式

Python 設計模式 建造者模式 範例一 class Product:     def __init__(self):        self.name=''       self.parameter1 = ''       self.parameter2 = ''       self.parameter3 = '' class Builder:    def __init__(self):       self.product = None     def SetName(self):        pass     def SetParameter1(self):        pass     def SetParameter2(self):        pass     def SetParameter3(self):        pass  class Product1Builder(Builder):     def SetName(self):        self.product.name = 'Product1'    def SetParameter(self):        self.product.parameter1 = '1-1'     def SetParameter(self):        self.product.parameter2 = '1-2'  ...