---
tags: for
---
<style>
div.list {
counter-reset: list-number;
font-weight: bold;
font-family:monospace;
margin-bottom: 20px;
}
div.list br {
margin-right: 20px;
}
div.list div:before {
counter-increment: list-number;
content: counter(list-number) ;
margin-right: 10px;
margin-bottom:10px;
margin-top:10px;
width:17px;
height:17px;
display:inline-flex;
align-items:center;
justify-content: center;
font-size:12px;
background-color: gray;
border-radius:50%;
color:white;
}
</style>
# 函式
```python=
def add(a, b) :
return a+b;
```
```python=
def hello_world() :
n = int( input() )
for i in range( n ):
print( "hello, world")
```
## 使用時機
需要重複用到很多次的`code`
讓複雜的程式比較容易看懂
```python=
def student_str( name, _cls, number ) :
return f"{name} 是 {_cls} 班 {number}號";
```
```python=
print(student_str("小明", 1, 1))
print(student_str("小華", 2, 4))
print(student_str("小孟", 3, 100))
print(student_str("小白", 4, 500))
```
<!--
```python=
print(student_str("小明", 1, 1))
print(student_str("小華", 2, 4))
print(student_str("小孟", 3, 100))
print(student_str("小白", 4, 500))
```
-->
# 函式庫使用
除了自己寫函式以外,其實已經有很多先人幫你寫好了許多方便的函示庫,
譬如`mathplotlib`, `math`, `pytorch`, `request`之類的東西,讓你可以站在巨人的肩膀上寫出需多炫酷的程式
# list使用
## list(array)
**主要函式**
<div class ="list">
<div>list.append()</div>
<div>list.clear()</div>
<div>list.copy()</div>
<div>list.count()</div>
<div>list.extend()</div>
<div>list.insert()</div>
<div>list.index()</div>
<div>list.pop()</div>
<div>list.remove()</div>
<div>list.reverse()</div>
<div>list.sort()</div>
</div>
```python=
lst = list()
lst.append() #插入
lst.clear() #清空
lst.copy() #複製
lst.count() #計數
lst.extend() #擴展
lst.insert() #插入
lst.index() #取位置
lst.pop() #移除最後一個元素
lst.remove() #移除元素
lst.reverse() #反轉
lst.sort() #排序
```
```python=
lst = [1, 2, 3]
'''
lst = []
lst = list()
這些初始化都是可以被接受的
'''
print( lst ) #[1, 2, 3]
print( lst[ 0 ]) # 1
# -------------------------- #
lst .append( 3 )
print( lst ) #[1, 2, 3, 3]
# -------------------------- #
lst .extend( [2, 4, 6])
print( lst ) #[1, 2, 3, 3, 2, 4, 6]
# -------------------------- #
lst .pop()
print( lst ) #[1, 2, 3, 3, 2, 4]
# -------------------------- #
lst .remove( 2 )
print( lst ) #[1, 3, 3, 2, 4]
# -------------------------- #
id = lst .index(4) # 4
print(id)
# -------------------------- #
id = 5 in lst
print(id) # False
# -------------------------- #
id = lst .index(5) if 5 in lst else -1
'''
等價於
id = -1
if 5 in lst :
id = lst .index( 5 )
'''
print(id) # -1
#--------------------------- #
```