3推倒或內涵
選擇語句的基本形式:
if 語句示例:if
《條件》:
語句elif
《條件》:
語句else:
語句
執行結果:age = input('please input your year: ')
age = int(age)
if age < 18:
print('未成年')
elif age >= 18
and age <= 25:
print('青年')
else:
print('老年人了!!!!')
please input your year: 26
老年人了!!!!
for 迴圈的基本形式:
①for 迴圈示例:for
《迴圈變數》 in
《遍歷物件》:
語句else:
語句
執行結果: 1 3for i in [1, 2, 3, 4, 5, 6, 7, 8]:
if i == 2:
continue
if i == 4:
break
print(i)
else:
print('程式結束')
②字典的遍歷示例:
執行結果:map =
#遍歷鍵和值
for key, value in map.items():
print(key, ': ', value, sep='', end='')
print(' ', sep='', end='')
print()
#遍歷鍵
for key in map.keys():
print(key, end='')
print(' ', sep='', end='')
print()
#遍歷值
for value in map.values():
print(value, end='')
print(' ', sep='', end='')
print()
a: 1 b: 2 c: 3 d: 4
a b c d
1 2 3 4
range()函式,產生乙個整數的列表;
for迴圈和range函式示例:執行結果:sum = 0
sum = 0
for i in range(0, 101):
sum += i
print('total is :', sum)
total is : 5050
內建迭代函式:
內建迭代函式示例:執行結果:lst1 = [2, 5, 1, 4, 8, 6]
lst2 = [5, 3, 2, 2, 4, 8]
# enumerate 函式
for index, value in enumerate(lst1):
print('index is %d, value is %d' % (index, value))
# sorted 函式
print(sorted(lst1))
#reversed 函式
for i in reversed(lst2):
print(i, end=' ')
print()
# zip函式
for i, j in zip(lst1, lst2):
print('i is %d, j is %d' % (i, j))
index is 0, value is 2
index is 1, value is 5
index is 2, value is 1
index is 3, value is 4
index is 4, value is 8
index is 5, value is 6
[1, 2, 4, 5, 6, 8]
8 4 2 2 3 5
i is 2, j is 5
i is 5, j is 3
i is 1, j is 2
i is 4, j is 2
i is 8, j is 4
i is 6, j is 8
while迴圈的基本形式:
while迴圈示例:while
《條件》:
《語句1>
else:
《語句2> #如果迴圈未被break退出,則執行
執行結果:# 使用while迴圈計算前100個數的和
i = 0
sum = 0
while i <= 100:
sum += i
i += 1
else:
print('overred')
print('totla is:', sum)
overred
totla is: 5050
這裡i += 1 同 i = i + 1基本形式:
推到示例:[ for i in aiterator ]
[ for i in aiterator if
《條件》 ]
執行結果:# 列表推倒,獲取0-10的平方的列表
lst = [i * i for i in range(0, 11)]
print(lst)
# 字典推倒,獲取字典
keys = ['name', 'age', 'weight']
values = ['douzhq', 26, 75]
map =
print(map)
# 帶條件推倒,獲取0-10的平方的偶數列表
lst = [i * i for i in range(0, 11) if i * i % 2 == 0]
print(lst)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[0, 4, 16, 36, 64, 100]
5 Python 語句和語法 賦值
概 述 賦值語句是程式設計世界裡最常見的語句。在python 中,擁有一些其他語言不具有的賦值技巧。python 語句賦值的基本形式是 在等號的左邊寫賦值語句的目標 在等式的右邊寫要賦值的物件。左側的目標可以是變數名或物件元素,而右側的物件可以是任何會計算得到的物件的表示式。需要注意 賦值語句建立物...
5 python學習 條件語句
程式語言一般都由這麼幾個部分組成 變數條件分支語句 迴圈語句 函式 這裡要說的就是條件分支語句。python的條件語句和shell指令碼的非常像,也就是ifelse ifelse這種形式,其中else if可以縮寫為elif。if 條件判斷1 執行1 elif 條件判斷2 執行2 elif 條件判斷...
5 python教程 函式
coding utf 8 表示檔案的編碼是utf8 fun1的函式體為空 需要使用pass語句佔位,因為函式體至少要有乙個句 對編寫框架程式有用處 def fun1 pass 乙個最簡單的函式,輸入乙個數,返回這個數的兩倍 def fun2 i return i 2 返回多個值,返回值是乙個元組 d...