1、for循環(huán)與條件語句:
除了Java中常見的for循環(huán)的寫法
chinese_zodiac ='鼠牛虎兔龍蛇馬羊猴雞狗豬'
# 常規(guī)形式一
for cz in chinese_zodiac:
print(cz)
# 常規(guī)形式二
for month in range(1,13)
print(month)
for year in range(2000,2019):
print('%s 年的生肖 %s',%(year,chinese_zodiac[year % 12]) )
# for嵌套if區(qū)別于Java,C++ 常規(guī)形式
list = [1, 2, 3, 4, 5, 6, 7]
list2 = []
for list_element in list:
if list_element % 2 != 0:
list2.append(list_element)
>>>> [1, 3, 5, 7]
# for嵌套for 常規(guī)形式
list = [1, 2, 3, 5, 8]
list_add = [2, 3, 5, 8]
list_results = []
for list_element in list:
for list_element_add in list_add:
list_results.append(list_element * list_element_add)
print(list_results)
>>>>> [2, 3, 5, 8, 4, 6, 10, 16, 6, 9, 15, 24, 10, 15, 25, 40, 16, 24, 40, 64]
# 既有if語句又有for嵌套 常規(guī)形式
for x in list:
if x % 2 == 0:
for y in list_add:
if y % 2 == 1:
list_results.append((x, y))
print(list_results)
>>> [(2, 3), (2, 5), (8, 3), (8, 5)]
還有另一種python的簡潔寫法
# for嵌套if 簡潔形式
list = [1, 2, 3, 4, 5, 6, 7]
list_new = [list_element for list_element in list if list_element % 2 != 0]
print(list_new)
>>>> [1, 3, 5, 7]
# for嵌套for 簡潔形式
list = [1, 2, 3, 5, 8]
list_add = [2, 3, 5, 8]
list_results = [list_element * list_element_add for list_element in list for list_element_add in list_add]
print(list_results)
>>>>> [2, 3, 5, 8, 4, 6, 10, 16, 6, 9, 15, 24, 10, 15, 25, 40, 16, 24, 40, 64]
# 既有if語句又有for嵌套 簡潔形式
list_results = [(x, y) for x in list if x % 2 == 0 for y in list_add if y % 2 == 1]
print(list_results)
>>> [(2, 3), (2, 5), (8, 3), (8, 5)]
2、if name == ' main':
區(qū)別于C++,Java,不需要顯示的提供main()函數(shù)入口,import在導入文件的時候,會自動把所有暴露在外面的代碼全部執(zhí)行一遍。因此,如果,要把一個東西封裝成模塊,又想讓他可以執(zhí)行的話,必須將要執(zhí)行的代碼放在if name == ' main'下面。name作為Python的魔術內(nèi)置參數(shù),本質(zhì)是模塊對象的一個屬性。我們使用import語句時,name就會被賦值為改模塊的名字,自然就不等于main