Python 基礎

2022/11/10閱讀時間約 11 分鐘

hello world

print('hello world')

Variable (變數)

a = 123 
type(a)
a = '456' 
type(a)
a = 3.13
type(a)

輸入 input()

a = input()
print('your name',a)

四則運算

a = int(input('數值1='))
b = int(input('數值2='))
print((10+(a*b)-1)/2)

列表 list (陣列)

list_num = [1, 2, 3]
list_length = len(list_num)	
num_sum = sum(list_num)
a = list_num[0]
print(list_length)
print(num_sum)
print(a)

集合

s = set()
s.add(1) # { 1 }
s.add(2) # { 1, 2 }
s.add(3) # { 1, 2 , 3 }
len(s) # 3
1 in s # True
print(s)

字典(Dictionary)

dict1 = {} # 建議寫法
dirct2 = dict()
grades = { 'a': 10, 'b': 20 }
grades['a']

給值

grades['c'] = 100
len(grades) # 3

try 檢驗

try:
	grade = grades['abc']
except KeyError:
	print('no grade for abc')
grades.get('abc', 40) # 若無則使用 default 值

取所有值

grades = { 'a': 10, 'b': 20 }
grades.keys() # 所有鍵值組成的 list
grades.values() # 所有值組成的 list
grades.items() # 所有鍵值組成的 tuple of list [('a', 10)]

判斷式 If else

score = int(input("score: "))
if score >= 90:
    print('Grade is: A')
elif score >= 80:
    print('Grade is: B')
elif score >= 70:
    print('Grade is: C')
elif score >= 60:
    print('Grade is: D')
else:
    print('Grade is: F')

迴圈

#for [變數名稱] in range(n): (縮排) print([變數名稱])
#for [變數名稱] in range(範圍, 比如從數字X到Y):    
#(縮排) 做一件事    
#(縮排) 做一件事
for x in range(10): # 0...9 不含 10
	if x == 3:
		continue
	if x == 5:
		break
	print(x)
cmp = ['google', 'facebook', 'youtube', 'yahoo']
for i in range(len(cmp)):
    print(cmp[i])
cmp = ['google', 'facebook', 'youtube', 'yahoo']
for i,cmps in enumerate(cmp):
    print(i, '-->', cmps)
names = ['lily', 'jojo', 'jojo', 'lily', 'lily', 'pk']
d = {}
#檢查 list 內有多少重複的字串
for n in names:
    if not n in d:
        d[n] = 0
        print('x=' , d) #初始賦予 {keys:0}
    d[n] += 1 
    print('y=' , d)
    
print(d)
x = 0
while x < 10:
	print('x is less than 10')
	x += 1

Switch //字典方式

#關鍵字 (keyword) lambda 是種將運算式 (expression) 重複運用的方式,類似函數 (function) 
#卻又不像函數需要額外命名函數的識別字 (identifier) ,因此又被稱為無名函數、匿名函數
#基本上 lambda 運算式就是函數的簡化,因此某些需要函數的場合可以用 lambda 運算式代替
a = lambda x: x ** 5 + 2
print(a)
print(a(2))
print(a(12))

def b():
    return lambda x: x + 2
c = b()
print(c)
print(c(18))

def sum(a, b, c = 0):
    print(a,b,c)
    return a + b + c
print(sum(10, 20, 30))   # 顯示 60
print(sum(10, 20))       # 顯示 30

x  = 10
{
  1: lambda y : y + 1,
  2: lambda y : y * 5
}[2](x)
score = int(input('請輸入分數:'))
level = score // 10
{
    10 : lambda: print('Perfect'),
    9  : lambda: print('A'),
    8  : lambda: print('B'),
    7  : lambda: print('C'),
    6  : lambda: print('D')
}.get(level, lambda: print('E'))()

CSV控制

寫入

import csv #引用 引入 csv 內建函示庫
# 開啟輸出的 CSV 檔案
with open('output.csv', 'w') as csvfile:
  # 建立 CSV 檔寫入器
  writer = csv.writer(csvfile)
  # 寫入一列資料
  writer.writerow(['姓名', '身高', '體重'])
  # 寫入另外幾列資料
  writer.writerow(['Joker', 175, 60])
  writer.writerow(['Hello', 165, 57])
讀寫模式的型別有: rU 或 Ua 以讀方式開啟, 同時提供通用換行符支援 (PEP 278) w 以寫方式開啟, a 以追加模式開啟 (從 EOF 開始, 必要時建立新檔案) r 以讀寫模式開啟 w 以讀寫模式開啟 a 以讀寫模式開啟 rb 以二進位制讀模式開啟 wb 以二進位制寫模式開啟 ab 以二進位制追加模式開啟 rb 以二進位制讀寫模式開啟 wb 以二進位制讀寫模式開啟 ab 以二進位制讀寫模式開啟

讀取

import csv
# 開啟 CSV 檔案
with open('output.csv') as csvfile:
  # 讀取 CSV 檔案內容
  rows = csv.reader(csvfile)
  # 以迴圈輸出每一列
  for row in rows:
    print(row)

import csv
with open('output.csv') as csvfile:
  # 讀取 CSV 檔內容,將每一列轉成一個 dictionary
  rows = csv.DictReader(csvfile)
  # 以迴圈輸出指定欄位
  for row in rows:
    print(row['姓名'], row['身高'], row['體重'])

pandas教學

詳細原碼: https://reurl.cc/qdOlEg

pandas x Apache Web Server

Windows下安裝
Apache + Python
01. 下載
02. 安裝
03. 設定 Apache 的設定檔httpd.conf
*********
首先
Ctrl+F 尋找
Options Indexes FollowSymLinks
在後面加上 ExecCGI
Options Indexes FollowSymLinks ExecCGI
Ctrl+F 尋找
AddHandler cgi-script .cgi
加上.py
AddHandler cgi-script .cgi .py
若發現有 # 的符號,代表不啟用
要把 # 給移除
Ctrl+F 尋找
DirectoryIndex index.php index.php3 index.html index.htm
增加 index.cgi index.py
修改完成後 存檔
最後
重新啟動 Apache
*********
04. pip 安裝套件
pip freeze
python -m pip install --upgrade pip
pip install matplotlib
pip install pandas
05. 執行範例
範例原碼: https://reurl.cc/Aq7dO3

request | 網路爬蟲

為什麼會看到廣告
38會員
129內容數
獨立遊戲開發紀錄
留言0
查看全部
發表第一個留言支持創作者!