0%

python筆記

1. 整數除法

1
2
print(7//3)
#2

2. 平方

1
2
print(2**4)
#16

3. 字串換行

1
2
3
4
print("""Hi,
How are you?
I'm fine.""")
#How are you?

4. 開根號

1
2
print(64**0.5)
#8.0

5. 3次方根

1
2
print(pow(8,1/3))
#2.0

6. LIST

6.1. length

1
2
3
fruits =["apple","orange","Guava"]
print(len(fruits))
#3

6.2. how to list remove range

1
2
3
4
5
6
7
8
9
10
11
12
fruits =["apple","orange","Guava"]
fruits[:2] = []
print(fruits)

#==result==
#['Guava']

```python
### how to set nested list

```python=
[[1,2,3],[4,5,6]]

7. what’s differnect list vs tuple ?

不能修改值

8. collections

1
2
collection_1 = {1,2,3}
collection_2 = {2,3,4}

8.1. 交集

1
2
print(collection_1 & collection_2)
#{2, 3}

8.2. 聯集

1
2
print(collection_1 | collection_2)
#{1, 2, 3, 4}

8.3. 差集

1
2
print(collection_1 - collection_2)
#{1}

8.4. 反交集

1
2
print(collection_1 ^ collection_2)
#{1, 4}

8.5. IN

1
2
print(2 in {1,2,3})
#True

9. string to list

1
2
3
4
5
6
7
8
name = "kite"*2
print(name)
name = set("kite"*2)
print(name)

#==result==
#kitekite
#{'i', 'e', 'k', 't'}

10. 從列表的資料產生字典

1
2
3
4
dic = { x:x*2 for x in[3,4,5] }
print(dic)
#==result==
#{3: 6, 4: 8, 5: 10}

11. 函式不定參數

1
2
3
4
5
6
7
8
def avg(*nums):
sum = 0
for num in nums:
sum = sum + num
return sum/len(nums)

print(avg(4,8))

12. 模組的概念

sys.path.append(“modules”)
sys.path

封包的設計與使用
專案檔案配置

  • 專案資料夾
  • 封包資料夾
    • init.py
      • 模組一.py
      • 模組二.py

import 封包名稱.模組名稱

13. 檔案操作

1
2
3
with open("config.json",mode="r") as file:
data = json.load(file)
print(data)
1
2
3
4
5
import json
with open("config.json",mode="w") as file:
data = json.load(file)
data["name"] = "kite"
json.dump(data,file)

14. 隨機數

1
2
3
4
5
6
7
8
9
10
11
12
import random
random.choice([0,1,5,8])
random.sample([0,1,5,8],2)
data = [0,1,5,8]
#洗牌
random.shuffle(data)
print(data)
#隨機數
random.random()
random.uniform(0.0,1.0)
#常態分配
random.normalvariate(100,10)

15. 平均數

1
2
import statistics
statistics.mean([1,4,6,9])

16. 中位數

1
2
import statistics
statistics.median([1,4,6,9])

17. 標準差

1
2
3
import statistics
#標準差 資料散部的狀況,資料間有沒有落差很大
statistics.stdev([1,4,6,9])