iT邦幫忙

DAY 7
0

Python初學起步走系列 第 7

[Python初學起步走-Day7] - 迴圈

  • 分享至 

  • twitterImage
  •  

Python 提供了 while 以及 for...in 迴圈

while迴圈語法:

while 布林條件式:

    ....

else:

    ....

else可以選擇用或不用,若布林條件式為True,while內的程式會一直被執行,直到布林條件式為False迴圈就被中止(正常中止)

然後執行else內的程式

然後執行else內的程式

然後執行else內的程式

很重要所以要講三次

while迴圈可以搭配 continue、break、pass

continue:使程式從迴圈的開始繼續執行

break:跳出迴圈

pass:什麼事都不做

舉個例子

算出1+3+5+7+9+11+13+15 = ?

i=1
ans=0
while i<=15:
	ans+=i
	i+=2
print(ans)

重複輸入,當輸入p則中止程式

while True:
	str = input("請輸入p結束")
	if str=="p":
		break


上一篇
[Python初學起步走-Day6] - 條件分支( if statement)
下一篇
[Python初學起步走-Day8] - 迴圈(續)
系列文
Python初學起步走30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
草原狼walfes
iT邦新手 5 級 ‧ 2019-08-12 13:23:06

前輩
ans4=0
for i in range(1,16,2):
ans4+=i
print(ans4) <---這個輸出沒有問題
64
我想輸出1+3+5+7+9+11+13+15 =64,用下列

print('1+3+5+7+9+11+13+15 =' + str(ans4))
出現TypeError: 'str' object is not callable
我的語法出現甚麼問題,該如何改進

我要留言

立即登入留言