iT邦幫忙

2024 iThome 鐵人賽

DAY 11
0

範例一:從1數到10
in後面加可迭代物件
range(1,11):包含1不包含11

for x in range(1,11):
    print(x)
    
1
2
3
4
5
6
7
8
9
10

範例二:從10讀到11並說happy new year!

for x in reversed(range(1,11)):
    print(x)
print("happy new year!")


10
9
8
7
6
5
4
3
2
1
happy new year!

範例三:跳過信用卡卡號dash
continue:跳過特定字串

credit_card ="1234-5678-9567-4671"
for x in credit_card:
    if x == '-':
        continue
    else:
        print(x)
        
        
1
2
3
4
5
6
7
8
9
5
6
7
4
6
7
1

範例四:終止繼續顯示迭代字串

credit_card ="1234-5678-9567-4671"
for x in credit_card:
    if x == '9':
        break
    else:
        print(x)


1
2
3
4
-
5
6
7
8
-

範例五:迭代字典
key:鍵,value:值
1.只迭代鍵

my_dictionary = {"a":1,"b":2,"c":3}
for x in my_dictionary:
    print(x)
    

a
b
c

2.迭代鍵和值

my_dictionary = {"a":1,"b":2,"c":3}
for key, value in my_dictionary.items():
    print("key:", key)
    print("value:",value)


key: a
value: 1
key: b
value: 2
key: c
value: 3

上一篇
Day 10: while 迴圈 + 複利計算機
下一篇
Day 12: 巢狀迴圈 + 碼錶實作
系列文
30天零基礎學習Python程式語言30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言