Python學習筆記 Day2

2022-05-15 18:44:21 字數 1884 閱讀 2655

在python中,for迴圈的功能十分強大,使用起來有些類似c++中的auto型別有些類似

for iterator in sequence #基本形式,iterator的型別和sequence的元素型別相同、

for i in "hello world":

print(i) #輸出字串中的每乙個字元

prime=[2,3,5,7,11,13]

for i in prime:

print(i) #輸出陣列中的每乙個元素

for i in range(len(prime)):

print(prime[i]) #另一種使用方法

for i in range(1,5):

print(i) #輸出[1,5)之間的數

for i in range(1,10,2):

print(i) #以2為間隔,輸出[1,10)之間的數

可以注意到,在for迴圈的使用中,range是乙個十分重要的組成部分,以下是range的使用方法

range(x) #只有乙個引數時表示[0,x)之間的整數,但是要注意,此時的i不會被初始化為0

range(a,b) #表示從[a,b)的所有整數

range(a,b,i)#表示以i為間隔,輸出[a,b)之間的數

與for同等級的else中,只有在for不是被break掉時才會執行else中的內容,例如以下**

#coding=utf8

prime=[2,3,5,7,11,13]

for i in range(14):

for j in range(0,len(prime)):

if prime[j]==i:

print(i,"is in the sequence")

break

else:

print(i,"is not in the sequence")

得到的預期輸出為:

0 is not in the sequence

1 is not in the sequence

2 is in the sequence

3 is in the sequence

4 is not in the sequence

5 is in the sequence

6 is not in the sequence

7 is in the sequence

8 is not in the sequence

9 is not in the sequence

10 is not in the sequence

11 is in the sequence

12 is not in the sequence

13 is in the sequence

可以看出只有在正常結束迴圈時,才會執行else中的語句

這是乙個簡單的while使用樣例,過於簡單不做講解:

#coding=utf8

i=0while i<5:

print(i)

i+=1

如果while中僅有一條語句,則可以和while寫在一行

只有在while正常執行完時才會執行else中的語句,例如以下**

#coding=utf8

i=0while i<5:

print(i)

i+=1

'''if i==3:

break

'''else:

print("running")

該程式執行時,將會輸出running,如果刪除注釋符,則當\(i=3\)時程式將會break,不會觸發else中的內容

python學習筆記 day2

函式之間或類的方法之間使用空行分隔,表示乙個新的開始,類和函式入口之間也用空行分隔。空格不是語法的一種,但是最好這樣做,為了方便閱讀和日後的維護 input n按下enter後退出 n value input n請輸入 n print value 接收輸入的資訊並列印python支援同一行內編寫多行...

Python學習筆記(day2) 雜談

今天看的知識挺雜的,主要還是集中在判斷語句和列表這一部分 分割線 1 多重判斷 if 和 elif 之間的區別在於占用記憶體不同。多個 if 要求電腦不斷重複判斷,而elif只需要一次判斷。大大提高了電腦讀寫 的速度 2 自增和自減運算。熟練掌握p 2,p 2的含義 3 input 只能接受乙個引數...

python學習筆記 day2 資料

py day2 資料 讀 python語言及其應用 做的筆記 目的 了解unicode,utf 8的不同,編碼,解碼方法。正規表示式部分感覺介紹的過於簡略了,所以沒有記錄,以後專門看正規表示式的時候再寫。1,文字字串 文字ascii使用7位 128種取值。unicode 使用若干個8bit的集合,稱...