iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

Python 基礎學習之旅系列 第 9

Day -9 while與for

while 常見用法如下:

//while 
count = 1
while count<=5:
  print(count)
  count += 1

// result 
1
2
3
4
5

//while break 
count = 1
while count != 6:
  print(count)
  count += 1
  if count > 5:
    break

//result
1
2
3
4
5


//while break continue     
count = 0
while count != 6:
  if count > 5:
    break
  count += 1
  if count % 2 == 0:
    continue
  print(count)

//result
1
3
5 

// while break continue & if else  
guess_me = 7
number = 1
while True:
  if number < guess_me:
    print('too low')
  elif number == guess_me:
    print('found it!')
    break
  else:
    print('oops')
    break
  number += 1
  
// result

too low
too low
too low
too low
too low
too low
found it!

guess_me = 7
for number in range(10):
  if number < guess_me:
    print('too low')
  elif number == guess_me:
    print('found it!')
    break
  else:
    print('oops')
    break
    
// result
too low
too low
too low
too low
too low
too low
too low
found it!

同樣的 guess_me = 7 for 會多顯示一次too low,其他常見for用法。

a =["A", "B", "C", "D", "E"]
for num in a:
  print(num)
  
// result
A
B
C
D
E
  
for num in range(10,0,-1):
  print(num)
 
// result
10
9
8
7
6
5
4
3
2
1

a = [0,9,2,2]
for num in a:
  print(num)
  
// result 
0
9
2
2
  • range(10) # 0 到10
0 1 2 3 4 5 6 7 8 9
  • 1, 11 # 1 到 11
1 2 3 4 5 6 7 8 9 10
  • range(0, 30, 5) # 每個值相差5
0  5 10 15 20 25

上一篇
Day-8 字串(下)
下一篇
Day -10 tuple與List
系列文
Python 基礎學習之旅12

尚未有邦友留言

立即登入留言