退出循環,什么時候用break好,什么時候加條件讓計算機自己判斷
比如說這個題,直接while n<21好像還方便些,實際編程的時候,什么時候用break會比較方便呢
sum = 0
x = 1
n = 1
while n < 21:
? ? sum = sum +x
? ? n = n+1
? ? x = x*2
print sum
比如說這個題,直接while n<21好像還方便些,實際編程的時候,什么時候用break會比較方便呢
sum = 0
x = 1
n = 1
while n < 21:
? ? sum = sum +x
? ? n = n+1
? ? x = x*2
print sum
2018-01-30
舉報
2018-01-30
我的理解是:在循環體中沒有明確的退出條件(如無限循環),用break來強制性跳出循環。
2018-01-31
不用break的話,理論上程序會無限執行下去
2018-01-31
????? #imooc網的爬蟲的調度程序
??? def craw(self, root_url):
??????? count = 1
??????? self.urls.add_new_url(root_url)
??????? while self.urls.has_new_url():
??????????? try:
??????????????? new_url = self.urls.get_new_url()
??????????????? print 'craw %d : %s' % (count, new_url)
??????????????? html_cont = self.downloader.download(new_url)
??????????????? #爬蟲解析器,傳入2個參數(當前url,下載完成的頁面數據)
??????????????? new_urls, new_data = self.parser.parse(new_url, html_cont)
??????????????? self.urls.add_new_urls(new_urls)
??????????????? self.outputer.collect_data(new_data)
??????????????? if count == 1000:
??????????????????? break
??????????????? count = count + 1
??????????? except:
??????????????? print 'craw failed'
??????? self.outputer.output_html()