---
# System prepended metadata

title: 第五週3/14
tags: [Python程式設計]

---

###### tags: `Python程式設計`

# 第五週3/14

## 串列
### 切片:用於取得特定範圍
```python=
lst=['a','b','c','d','e']
print(lst[1:3])

['b', 'c']
```
### 新增元素
```python=
lst=['a','b','c','d','e']
lst[2]='x'
lst.append('c')
print(lst)

['a', 'b', 'x', 'd', 'e', 'c']
```
### 刪除元素
```python=
lst=['a','b','c','d','e']
lst[2]='y'
lst.remove('b')
print(lst)

['a', 'y', 'd', 'e']
```
### 計算元素的出現次數
```python=
1st=['a','b','c','d','e','c','c']
print(1st.count('c'))

3
```
### 迴圈
迴圈是指在串列裡每個元素皆走訪一遍，然後印出符合條件的元素。
```python=
lst=['a','b','c','d','e','f','g']
#針對lst中的每個元素i(我們用i代表每個元素)
#loop
#走訪串列的每個元素
for i in lst:
 print(i)

a
b
c
d
e
f
g
```
```python=
a=(1,2,3,4,5)
for x in a:
  print('in for loop')
  if x>3:
    print(x)
    
in for loop
in for loop
in for loop
in for loop
4
in for loop
5
```
回家作業:算出串列數字的總和
```python=
a=[1,2,3,4]
b=0
for x in a:
  print( 'x=' )
  print( x )
  b=b+x
  print( 'b=' )
  print( b )
  print("---------")
print(b)

x=
1
b=
1
---------
x=
2
b=
3
---------
x=
3
b=
6
---------
x=
4
b=
10
---------
10
```
回家作業:找出串列中的最大值
```python=
a=(1,2,3,4)
max_val=None
for x in a:
 if(max_val is None or x>max_val):
   max_val=x
print(max_val)

4
```







