兩種循環
1.for...in循環
nums = ['0000', '1111', '2222']
for num in nums:
print(num)
2.while循環
sum = 0
n = 100
while n > 0:
sum = sum + n
n = n - 1
print(sum)
break語句可以在循環過程中直接退出循環,而continue語句可以提前結束本輪循環,并直接開始下一輪循環。
dict字典
people = {'Jerry': 21, 'Tom': 25, 'Tony': 47}
print(people['Jerry'])
people['Tom']=28 #設置鍵值
print(people['Tom']) #28
print('kelly' in people) #判斷Key是否存在print(d.get('Thomas')) false
print(people.get('kelly')) #判斷Key是否存在 不存在返回none或者自己指定的value none
print(people.get('kelly',-2)) #不存在返回自己指定的value -2
people.pop('Tom') #刪除一個key
print(people) # {'Jerry': 21, 'Tony': 47}
dict全稱dictionary,在其他語言中稱為map,使用鍵-值(key-value)存儲,優點是具有極快的查找速度。
注意:dict內部存放的順序和key放入的順序是沒有關系的
和list比較,dict有以下幾個特點:
1.查找和插入的速度極快,不會隨著key的增加而變慢;
2.需要占用大量的內存,內存浪費多。
而list相反:
1.查找和插入的時間隨著元素的增加而增加;
2.占用空間小,浪費內存很少。
所以,dict是用空間來換取時間的一種方法。
set
set和dict類似,也是一組key的集合,不存儲value,并且key值不能重復。
s = set([1, 2, 3,4,5,4,3,4,2,1])
print(s) #{1, 2, 3, 4, 5}
add(key)添加元素
s.add('55')
print(s) #{1, 2, 3, 4, 5, '55'}
remove(key)刪除元素
s.remove(4)
print(s) #{1, 2, 3, 5, '55'}
函數
print(abs(-22)) # 絕對值 22
函數
定義一個函數要使用def語句,依次寫出函數名、括號、括號中的參數和冒號:,然后,在縮進塊中編寫函數體,函數的返回值用return語句返回。
demo:
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
print(my_abs(777)) #777
print(my_abs(-999)) #999
def calc(numbers): #參數
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print(calc([2,5,7,9,4])) #計算a*a+b*b+...的和
def calc(*numbers): #*表示可變參數,可以不傳
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print(calc(22,6,7,8,9,10)) #814
print(calc()) #0
迭代
for i, value in enumerate(['A', 'B', 'C']):
print(value)