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