CS50P 2_Loop
poetries = ["寥落古行宮,宮花寂寞紅。白頭宮女在,閒坐說玄宗。",
"空山不見人,但聞人語響。返景入深林,復照青苔上。",
"床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。"]
print(poetries[0])
print(poetries[1])
print(poetries[2])
寥落古行宮,宮花寂寞紅。白頭宮女在,閒坐說玄宗。
空山不見人,但聞人語響。返景入深林,復照青苔上。
床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。
poetries = ["寥落古行宮,宮花寂寞紅。白頭宮女在,閒坐說玄宗。",
"空山不見人,但聞人語響。返景入深林,復照青苔上。",
"床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。"]
for i in range(0,3):
print(poetries[i])
寥落古行宮,宮花寂寞紅。白頭宮女在,閒坐說玄宗。
空山不見人,但聞人語響。返景入深林,復照青苔上。
床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。
poetries = ["寥落古行宮,宮花寂寞紅。白頭宮女在,閒坐說玄宗。",
"空山不見人,但聞人語響。返景入深林,復照青苔上。",
"床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。"]
for poetry in poetries:
print(poetry)
寥落古行宮,宮花寂寞紅。白頭宮女在,閒坐說玄宗。
空山不見人,但聞人語響。返景入深林,復照青苔上。
床前明月光,疑是地上霜。舉頭望明月,低頭思故鄉。
Loop 迴圈
重複執行某些相同的步驟
固定次數 for loop
指定條件 不固定次數 while loop
For Loop Structure
for _ in sequence:
do repeat things
...
_ indicates we're not interested in the loop variable. It's a common convention when the value is ignored.
for _ in range(5):
print("***")
***
***
***
***
***
For Loop Structure
for i in sequence:
do repeat things
...
Using "i" means we are actually utilizing the loop variable within the loop.
for i in range(1, 6):
print("*"*i)
*
**
***
****
*****
range() function
The range() function can create a sequence of integers.
range(start value, end value (excluding), increment (decrement) value)
range(end value)
range(start value, end value)
range(start value, end value, increment (decrement) value)
range() example
for i in range(10): # 產生從0到9的整數序列
print(i, end=" ")
print("\n=========================")
for i in range(0, 10): # 產生從0到9的整數序列
print(i, end=" ")
print("\n=========================")
for i in range(1, 10, 2): # 產生從1到9的奇數序列
print(i, end=" ")
print("\n=========================")
for i in range(20, 0, -2): #產生從20到2的偶數序列
print(i, end=" ")
0 1 2 3 4 5 6 7 8 9
=========================
0 1 2 3 4 5 6 7 8 9
=========================
1 3 5 7 9
=========================
20 18 16 14 12 10 8 6 4 2
Nested for loop (巢狀 for-loop)
Multiple layers of for loops.
for i in sequece:
do repeat things
for j in sequece:
do repeat things
...
For each iteration of the outer loop i,
the inner loop j executes the entire loop.
Multiplication Table of 9
for i in range(1, 10):
print(f" i = {i}", end = ' ')
for j in range(1, 10):
if j == 9:
print(f"{i*j:5}") # j == 9時,換行
else:
print(f"{i*j:5}", end = '') # j < 9時,不換行
i = 1 1 2 3 4 5 6 7 8 9
i = 2 2 4 6 8 10 12 14 16 18
i = 3 3 6 9 12 15 18 21 24 27
i = 4 4 8 12 16 20 24 28 32 36
i = 5 5 10 15 20 25 30 35 40 45
i = 6 6 12 18 24 30 36 42 48 54
i = 7 7 14 21 28 35 42 49 56 63
i = 8 8 16 24 32 40 48 56 64 72
i = 9 9 18 27 36 45 54 63 72 81
break 和 continue
強制中斷的方式來結束迴圈
break:
中斷迴圈的執行並跳脫迴圈結構,繼續執行迴圈外的敘述。
continue:
不會讓迴圈結束;只跳過迴圈內 continue 後面的剩餘敘述,接著繼續執行下一次的迴圈運作。
break
for i in sequence:
# statements inside for-loop
if condition:
break # Exit the loop
# statements inside for-loop (after the break)
# statements outside for-loop
for i in "Hey Jude":
if i == "u":
break
print(i, end = "")
Hey J
break
Continue
for i in sequence:
# statements inside for-loop
if condition:
continue # Skip the rest of this iteration and
# jump to the next iteration
# statements inside for-loop (after the continue)
# statements outside for-loop
for i in "Hey Jude":
if i == "u":
continue
print(i, end = "")
Hey Jde
Continue
while loops
無法預知迴圈數 直到出現指定的特殊狀況時才停止
當 ... 的時候 直到 ...
while condition:
do condition True things
while loop check 成績
score = int(input("輸入學生成績:"))
while score < 0 or score > 100:
score = int(input("成績錯誤,請重新輸入:"))
print("學生成績 : ", score)
輸入學生成績: -120
成績錯誤,請重新輸入: 120
成績錯誤,請重新輸入: 50
學生成績 : 50
無窮迴圈
一直持續下去的循環
while True:
do something
while True:
print('How is your day?')
your_reply = input()
if your_reply == 'quit':
break
print('good bye')
while loop check username & password
while True:
print('Account name:')
name = input()
if name != 'success':
continue
print('Password, please:')
password = input()
if password == 'selflearning':
break
print('Welcome to Self Learning Success!')
For loop Access Dictionary
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for key in knights:
print(f" key: {key}")
key: gallahad
key: robin
For loop Access Dictionary
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for key in knights:
print(f"key: {key}\nknights{[key]} : {knights[key]}")
key: gallahad
knights['gallahad'] : the pure
key: robin
knights['robin'] : the brave
For loop Access Dictionary
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(f"knights[{k}] : {v}")
knights[gallahad] : the pure
knights[robin] : the brave
enumerate() function
s = ['tic', 'tac', 'toe']
print(f"list is {s}\n")
for i, v in enumerate(s):
print(f"index i = {i}, value v = {v}")
list is ['tic', 'tac', 'toe']
index i = 0, value v = tic
index i = 1, value v = tac
index i = 2, value v = toe
CS50P 2_Loop
By wschen
CS50P 2_Loop
This presentation covers topics such as loops, the range() function, nested for loops, break and continue statements, while loops, and accessing dictionaries with for loops. Discover how these concepts can enhance your programming skills and make your code more efficient.
- 240