Python 循環(huán)的for語(yǔ)句【每日一個(gè)知識(shí)點(diǎn)第205期-Python】
Python for循環(huán)可以遍歷任何序列的項(xiàng)目,如一個(gè)列表或者一個(gè)字符串。
for循環(huán)的一般格式如下:
for <variable> in <sequence>: <statements> else: <statements>
Python loop循環(huán)實(shí)例:
實(shí)例
>>>languages = ["C", "C++", "Perl", "Python"] >>> for x in languages: ... print (x) ... C C++ Perl Python >>>
以下 for 實(shí)例中使用了 break 語(yǔ)句,break 語(yǔ)句用于跳出當(dāng)前循環(huán)體:
實(shí)例
#!/usr/bin/Python3 sites = ["Baidu", "Google","Runoob","Taobao"] for site in sites: if site == "Runoob": print("菜鳥教程!") break print("循環(huán)數(shù)據(jù) " + site) else: print("沒有循環(huán)數(shù)據(jù)!") print("完成循環(huán)!")
執(zhí)行腳本后,在循環(huán)到 "Runoob"時(shí)會(huì)跳出循環(huán)體:
循環(huán)數(shù)據(jù) Baidu 循環(huán)數(shù)據(jù) Google 菜鳥教程! 完成循環(huán)!
《Python入門每日一個(gè)知識(shí)點(diǎn)》欄目是馬哥教育Python年薪20萬(wàn)+的學(xué)員社群特別發(fā)起,分享Python工具、Python語(yǔ)法、Python項(xiàng)目等知識(shí)點(diǎn),幫助大家快速的了解Python學(xué)習(xí),快速步入Python高薪的快車道。