如果while的條件總是成立,我們稱其為無窮迴圈.
使用時機:當我們的程式需要等待使用者的一些要求時
while True:
print “never stop”
而break 跟 continue 則可以強制介入迴圈
n = 5
count = 1
while True:
print "just print {} times".format(count)
if count == n:
break
count+=1
continue 的用法
n = 1
while n<=10:
if n==5:
n+=1
continue
print n
n+=1
for 迴圈
lst = [1,2,3]
for num in lst:
print num
for item in lst:
suite
將lst中的元素一個個取出,每取出一個便將他賦值(代入)
並且執行一次suite
for 可以對清單 元組 字典 字串 進行迭代
使用時機
for :當重複的次數可以被計算時
while:當條件清楚時
comprehension
lst = [1,2,3,4,5]
lst_eq = [n**2 for n in lst]
lst_eq1=[n**2 for n in lst if n%2==0]
>>>lst_eq
[1,4,9,16,25]
>>>lst_eq1
[4,16]
scores = [88,90,100,65,78]
score_dic = {student_id :score for student_id,score in enumerate(scores)}
>>>score_dic
{0: 88, 1: 90, 2: 100, 3: 65, 4: 78}
enumerate是一個函數,當它與for 搭配時,他會同時把索引值與元素取出
1.7 輸入與輸出
print函式
1.任何基本資料都可以用print輸出
2.print 1,———不斷行列印 加逗號
input函式
guess = 6
while True:
guess_number = int(input('please enter a num \n'))
if guess_number == guess:
print "right"
break
else:
print “wrong"
注意:任何輸入都會被當成字串,需要轉換
沒有留言:
張貼留言