$ python
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
...
>>> import this
The Zen of Python, by Tim Peters
優美優於醜陋。明瞭優於隱晦。
簡單優於複雜。複雜優於凌亂。
扁平優於巢狀。稀疏優於稠密。
可讀性很重要。
...
print("Hello, World.")
print("Hello, World.")
#include <stdio.h>
int main(){
printf("Hello, World.\n");
return 0;
}
l = [x for x in range(100) if x % 3 == 0 and x % 7 == 0]
l = [x for x in range(100) if x % 3 == 0 and x % 7 == 0]
int l[100] = {0};
int size = 0;
for(int i = 0;i < 100;i++){
if(i % 3 == 0 && i % 7 == 0){
size[i - 1] = i;
size++;
}
}
$ cd ~ # 回到使用者家目錄
$ mkdir c2python # 建立 c2python 目錄
$ cd ./c2python # 切換進入目錄
$ python
$ code
$ cd ~
$ git clone https://github.com/yuto0226/FromC2Python.git
打開你的終端機
$ python # python3
進入Python 直譯器的介面
>>>
...
與 Python 直譯器互動
>>> 1 + 1
2
>>> x = 42
>>> x ** 2
1764
>>> x = x ** 2 + 5
>>> x
與 Python 直譯器互動
>>> 1 + 1
2
>>> x = 42
>>> x ** 2
1764
>>> x = x ** 2 + 5
>>> x
1769
>>>
import math
>>> r = 18
>>> r = 18
>>> r ** 2 * math.pi
1017.8760197630929
>>> Yuto = True
>>> handsome = True
>>> Yuto = True
>>> handsome = True
>>> if Yuto is handsome:
... print("Yuto is handsome.")
... else:
... print("Yuto is ugly.")
...
>>> Yuto = True
>>> handsome = True
>>> if Yuto is handsome:
... print("Yuto is handsome.")
... else:
... print("Yuto is ugly.")
...
Yuto is handsome.
>>> ^Z # Crtl+z或quit()
輸入 Ctrl + Z (=EOF)或 quit() 退出 Python 直譯器
$ cd ~/c2python/
$ code io.py
VS code
# io.py
x = input("請輸入 x: ")
print(x)
Shell
$ python io.py
請輸入 x: 123
123
input(prompt)
如果有傳入 prompt參數則會在 sys.stdout 印出 prompt(不換行)
input() 會從 sys.stdin 讀取一行轉換成字串
print(*objects, sep=' ', end='\n', file=None, flush=False)
Print objects to the text stream file, separated by sep and followed by end. sep, end, file, and flush, if present, must be given as keyword arguments.
print(*objects, sep=' ', end='\n', file=None, flush=False)
寫一個程式,會從終端機輸入一個字串,請將字串用 print() 印出。
"Hello," 會做為第一個參數,第二個參數則是輸入的字串。
最終的結果將是 "Hello, <輸入的字串>!"。
# 註解會打在 # 的後面
# Python 沒有多行註解
print() # 這行會印出一個 '\n'
儲存資料的容器
# 宣告變數時不用指定型別
# 一個變數可以裝不同型別的資料
num, flt = 31, 4.2
num = "TTUSSC"
flt = [1, 1, 2, 3, 5, 8, 13] # 費氏數列
型別轉換
# 型別(轉換的目標)
data = "2024"
print(type(data), data)
data = int(data)
print(type(data), data)
型別轉換
# 型別(轉換的目標)
data = "2024"
print(type(data), data)
# <class 'str'> 2024
data = int(data)
print(type(data), data)
# <class 'int'> 2024
總結來講,Python 變數就是
可以把它視為自由調整大小的陣列,同時還可以裝不同類型的資料。
list 會用中括號把元素包起來,元素之間用 , 分隔
l = [1, 1, 2, 3, 5, 8, 13]
l = ["莛宥", 180, 65.2, [123, "威翰"]]
print(l[0][0]) # '莛'
print(l[2]) # 65.2
print(l[-1]) # [123, "威翰"]
list 的操作
a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8, 10]
print(a + b) # [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
a.append(2**3)
print(a) # [1, 3, 5, 7, 9, 8]
字串和 C 一樣,用雙引號包住
0 1 2 3 4 5
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
-6 -5 -4 -3 -2 -1
l = "Python"
Python 合法的字串形式
print('spam eggs') # spam eggs
print("Paris rabbit!") # Paris rabbit!
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
# Usage: thingy [OPTIONS]
# -h Display this usage message
# -H hostname Hostname to connect to
str 的操作
first = "Elon"
last = "Ma"
print(first + " " + last) # Elon Ma
pritn(last * 3) # MaMaMa
list 的切分
>>> # l[開始:結尾:間隔]
>>> l = "Python"
>>> l[1:5]
'ytho'
0 1 2 3 4 5
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
^ ^
|---- 這中間 ----|
list 的切分
# l[開始:結尾:間隔]
a = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(a[2:7]) # [2, 3, 4, 5, 6]
print(a[::2]) # [0, 2, 4, 6, 8]
print(a[::-1]) # [8, 7, 6, 5, 4, 3, 2, 1, 0]
撰寫一個程式,會輸入一個字串(len > 3)。分別將字串進行操作,
- 倒著印出來
- 跳一格印出
- 字串切最前面兩個字元
字串切最後三個字元
ex. "stanley"
yelnats
saly
st
ley
Hint: 使用 len(串列)
可以取得其元素個數
撰寫一個 BMI 計算機(bmi.py),會有兩行輸入:身高(cm)、體重(KG),
輸出 BMI 值。
請輸入身高:167
請輸入體重:51
BMI 是:18.286779733945284
Extra:小數點取兩位可以怎麼做?
if 條件:
# do something
elif 條件:
# do something
else:
#do something
if(條件){
// do something
}else if(條件){
// do something
}else{
// do something
}
撰寫一個程式,解出 \( ax^2 + bx + c = 0 \) 的解。
有三個輸入 a, b, c,
若兩個根不同印出 "Two different roots x1=?? , x2=??",
若兩同根則印出 "Two same roots x=??",
若無實數解則印出 "No real root"。
a006. 一元二次方程式
$ cd ~/RromC2Python/example
$ python ./hello.py
$ cd ~/RromC2Python/example
$ python ./hello.py
Hello, World
$ python ./hello.py <自己的名字>
$ python ./hello.py 自己的名字
Hello, 自己的名字
# hello_python.py
import sys
def main(argv):
if len(argv) > 1:
print(f"Hello, {argv[1]}")
else:
print("Hello, World")
if __name__ == "__main__":
main(sys.argv)
# hello_python.py
import sys
def main(argv):
if len(argv) > 1:
print(f"Hello, {argv[1]}")
else:
print("Hello, World")
if __name__ == "__main__":
main(sys.argv)
// hello_python.c
#include <stdio.h>
int main(int argc, char* argv[]){
printf("Hello, %s", argc > 1 ? argv[0] : "World");
return 0;
}
__main__ --- 頂層程式碼環境
# hello_python.py
import sys
def main(argv):
if len(argv) > 1:
print(f"Hello, {argv[1]}")
else:
print("Hello, World")
if __name__ == "__main__":
main(sys.argv)
// hello_python.c
#include <stdio.h>
int main(int argc, char* argv[]){
printf("Hello, %s", argc > 1 ? argv[0] : "World");
return 0;
}
__main__ --- 頂層程式碼環境
while 條件:
# do something
撰寫一個程式,計算(((1+1)*2+1)*2+1)...,直到數字是71的倍數為止。
判斷其值是否為三的倍數。
for 元素 in 串列:
# do something
for 元素 in 串列:
# do something
group = ["Stanley", "York", "Wayne", "Ruby"]
for people in group:
print(people)
for 元素 in 串列:
# do something
group = ["Stanley", "York", "Wayne", "Ruby"]
for people in group:
print(people)
string str = "Allen";
for(char ch:str){
std::cout >> ch;
}
range(開始,結束,間隔)
>>> list(range(1,5))
[1, 2, 3, 4]
for i in range(5):
print(i)
for(int i = 0;i < 5; i++){
printf("%d\n",i);
}
撰寫一個程式,輸入一個數字 n 計算 1 + 2 + 3 + ... + n,
以及 n!
a244. 新手訓練 ~ for + if
while True:
x = input()
if x == '':
break
print(x)
輸入任意字串直到輸入空字串為止
for i in range(100):
if i % 13 == 0:
continue
print(i)
跳過印出13的倍數的值
for i in range(1000000):
pass
1000000 次的空迴圈
d = {鍵:資料}
print(d[鍵]) # 資料
d[鍵] = 新資料
d[新鍵] = 資料 # 新增資料
grade = {
"discrete":56, "java":95,
"android":100, "english":78
}
print(grade["discrete"]) # 56
print("java" in grade) # True
print("english" not in grade) # False
print(list(grade))
# ['discrete', 'java', 'android', 'english']
print(list(grade.values()))
# [56, 95, 100, 78]
grade["news_eng"] = 66
print(grade)
# {
# 'discrete': 56, 'java': 95,
# 'android': 100, 'english': 78, 'news_eng': 66
# }
del grade["english"]
print(grade)
# {
# 'discrete': 56, 'java': 95,
# 'android': 100, 'news_eng': 66
# }
撰寫一個字典程式可以自由的新增單字以及修改單字。
輸入 a 新增/修改單字,
輸入 l 印出目標單字,若無資料則印出"查無單字",
輸入 p 印出所有單字,
輸入 q 退出
a
請輸入單字:array
請輸入中文:陣列
l
請輸入單字:array
陣列
p
...
q
def 函式名稱(參數):
[return 回傳值]
def 函式名稱(參數):
[return 回傳值]
def 函式名稱(參數: 參數型別)->回傳值型別:
[return 回傳值]
撰寫一個函式 mid() 會接收一個沒有排序的 list,
回傳這組 list 的中位數的值。
Vito's family
https://
yuto0226
.
github
.
io
/
FromC2Python
/
slide.html #Internet ?topic=網際網路and爬蟲&content=url
$ ipconfig
HTTP request
GET / HTTP/1.1\r\n
Host: i4010.isrcttu.net:9996\r\n
\r\n
HTTP responce
HTTP/1.1 200 OK\r\n
Server: nginx/1.24.0\r\n
Date: Thu, 09 May 2024 03:26:19 GMT\r\n
Content-Type: text/html; charset=UTF-8\r\n
Transfer-Encoding: chunked\r\n
Connection: keep-alive\r\n
\r\n
Requests is an elegant and simple HTTP library for Python, built for human beings.
$ pip install requests
import requests
url = "i4010.isrcttu.net"
r = requests.get(url)
print(r)
print(r.headers)
print(r.text)
Beautiful Soup is a Python library for pulling data out of HTML and XML files.
$ pip install beautifulsoup4
root = "https://www.ptt.cc"
q = "/bbs/Food/index.html"
import requests
r = requests.get(root + q)
print("responce:", r)
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.text, "html.parser")
titles = soup.find_all("div", class_="title")
for line in titles:
print(line.a.get_text())
print(root + line.a["href"])