基礎Python

python介紹

特色:

  • 直譯式語言

  • 對空白、換行敏感

  • 套件豐富

  • 有點慢(?

  • 語法簡單

小知識:編譯式與直譯式

編譯:
把我們看的懂的(程式語言)變成
電腦看得懂的(電腦指令)

編譯式:編譯完再執行

直譯式:邊執行邊編譯

python IDE

學校有的:python IDLE

回家時推薦的:

visual studio

visual studio code

jupyter notebook(大推

教學:

講師私推jupyter notebook時間

jupyter notebook好處:


1.多個程式語言整合

2.cell分區塊,可以區分功能、分區執行

3.可以用cmd快速下載、移除python套件

  • 線上編輯器
  • 長的跟Jupyter Notebook很像
  • 下節課土厚學長會教你們裝本機的
  • 不能用學校帳號登入

輸入輸出

輸出

就直接print()

print(你要印的東西)
  • 字串記得加 " " 或 ' '
  • 會自動帶一個換行
print(A, B, sep = ',', end = 'XD')
  • 可以印很多東西,用 , 隔開
  • sep : 分隔AB的符號,預設' '
  • end :  全部印完的結束符號,預設'\n'

小練習-1

Hello World!

輸出"Hello World!"

print("Hello World!")

輸入

input()

s = input()
  • 讀到換行
  • 讀進來的是字串

小練習-2

讀一個字串,然後把它印出來

s = input()
print(s)

註解

comments

#iamweak

'''
iamweak
'''

引入函式庫

函式庫:

想要用模組就需要引入!

import math
  • 引入整個函式庫
  • 要加函式庫名稱
import math as mh
  • 幫函式庫取綽號

ex.math 中的sqrt

import math

a=2
print(math.sqrt(a))

#result: 1.4142135623730951

另一種引入方式

from math import sqrt
  • 引入函式庫中的特定函式
  • 不用加函式庫名稱
from math import sqrt as sq
  • 幫函式取綽號
from math import *
  • 引入函式庫中的所有函式
  • 不用加函式庫名稱
  • 不可以取綽號

ex: 還是math 中的sqrt

from math import sqrt as rt

a=2
print(rt(a))

#result: 1.4142135623730951

變數

與C++比較

python C++
不用宣告 要宣告
不能取關鍵字 不能取關鍵字
有分全域、區域 有分全域、區域

小知識:全域與區域

全域:整份code都會存在他

區域:只有一個區域會有他

這個概念可以先留著,之後會再作解釋

變數

  • 儲存資料
  • 名稱可以是英文、數字、底線
  • 大小寫視為不同
  • 不用宣告
  • 動態型別
  • 數字 : int、float、complex

  • 文字 : char、str

  • 布林值 : bool

  • 容器 : list、tuple、range、dict

  • 集合 : set、frozenset

資料型態列表

注意:

以下變數都有很多細節的用法
簡報上就不列出來了
詳情請見w3school

取得變數的資料型態

print(type('dolphin'))

# result:<class 'str'>

pi = 3.14
print(type(pi))

# result:<class 'float'>

str

a = "linkiorz"
print(a)

#result: linkiorz

chr

  • 字元
  • ASCII將數字對應到字元
  • 字串
  • 一串字元
  • 用 "" 或 '' 括起來

int

float

  • 整數

complex

x = 123
print(type(x))
#result: <class 'int'>

y = 1.23
print(type(y))
#result: <class 'float'>

z = 1+1j
print(type(x))
#result: <class 'complex'>
  • 浮點數
  • 會有誤差
  • 複數
  • 以 \(a + bj\)的形式表示

bool

只有零跟一的型態

a=True 
a=False

困難部分

接下來的變數我們會用

資料結構

來叫它們

tuple

thistuple = ("dolphin", "knight", True, 4, "color", "color")
len(thistuple)    # 6
thistuple[0]    # "dolphin"
  • 元組(??) a.k.a. 陣列
  • 用()包起來
  • 有序
  • 不可改變
  • 允許重複值
  • 允許同一個tuple中有不同型態元素

list

thislist = ["dolphin", "knight", True, 4, "color", "color"]
len(thislist)    # 6
thislist[0]    # "dolphin"
thislist.append(7122)
thislist.insert("bad", 0)
thislist.pop(0)
thislist.remove("color")
thislist.reverse()
  • 串列(??) a.k.a. 陣列
  • 用[]包起來
  • 有序
  • 可改變
  • 允許重複值
  • 允許同一個list中有不同型態元素

range

  • 整數序列!
  • range(起始值, 終止值, 步進值)
  • 起始值預設0, 可省略
  • 終止值不可省略
  • 步進值預設1, 可省略
  • 包含起始值,不含終止值
print(range(-5,5,2))

#result: range(-5,5,2)
for i in range(5):
	print(i)
'''
result:0
1
2
3
4
'''
for i in range(2,5):
	print(i)
'''
result:2
3
4
'''
for i in range(-5,5,2):
	print(i)
'''
result:-5
-3
-1
1
3
'''

dictionary

  • 一個鍵值(key)對應一個值(value)
  • 以{key:value}建立
  • 內容可改變
  • 不允許重複key
thisdict = {
  "Jerry": "dolphin knight",
  "color": True,
  "num": 7122
}
print(thisdict["color"])

#result: True

set frozenset

就是數學中的集合

frozenset不可修改,set可以

簡單來說,集合就是一個群體

ex.一個班級也是集合

班級中的學生就是集合中的元素

表示法(數學):

集合\(A\)和他的元素可以用以下符號表示
\(A=\{1,2,3\}\)

A = {1,2,3}

code:

接下來會用文氏圖來解釋

z

x

y

定義:

\(A\)=x+z
\(B\)=y+z

z

x

y

交集:

\(A \cap B\)=z

z

x

y

A={1,2,3}
B={2,3,4}
A=A.intersection(B)
print(A)
#result: {2, 3}

聯集:

\(A \cup B\)=x+y+z

z

x

y

A={1,2,3}
B={2,3,4}
A=A.union(B)
print(A)
#result: {1, 2, 3, 4}

差集:

\(A\)-\(B\)

=\(A\)-\(A \cap B\)=x

z

x

y

A={1,2,3}
B={2,3,4}
A=A.diference(B)
print(A)
#result: {1}

型別轉換

x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

轉int

用這個方法我們就可以把input()進來的東西轉成數運算了

x = float(1)     # x will be 1.0
y = float(2.8)   # y will be 2.8
z = float("3")   # z will be 3.0
w = float("4.2") # w will be 4.2

轉float

轉string

x = str("s1") # x will be 's1'
y = str(2)    # y will be '2'
z = str(3.0)  # z will be '3.0'

同理也會有

a = (7, 1, 2, 2)
print(list(a))

轉list

a = [7, 1, 2, 2]
print(tuple(a))

轉tuple

a = [("one", 1), ("two", 2), ("three", 3)]
print(dict(a))

轉dict

運算子

operator

=

把等號右邊的值指定給左邊的變數

a = 7122
b = 3.14
c = "dolphin"

加減乘除

a = 7
b = 3
c = a + b    # 10
d = a - b    # 4
e = a * b    # 21
f = a / b    # 2.333333333333333

對float也可以這樣做

另一種風貌的加減乘除

s1 = "dolphin"
s2 = "knight"

s3 = s1 + s2    # "dolphinknight"
s4 = s1 * 3    # "dolphindolphindolphin"

對string 做加法、乘法

  • 字串A + 字串B = 連結AB字串
  • 字串A * 整數N = A重複N次

除法取整數

a//b=\( \lfloor\frac{a}{b}\rfloor\)

a = 5
b = 2

c = a // b    # 2

a, b可以是int, float

次方

a = 5
b = 2

c = a ** b    # 25

a ** b = \(a^b\)

a, b可以是int, float

甚至負數(!

取餘數

a = 10
b = 3

c = a % b    # 1

a % b : a 除以 b 的餘數

python的 % 出來在0~b - 1之間

運算子加=

a = a + b
a += b

a = a - b
a -= b

a = a * b
a *= b

以下算式兩個一組等價

a = a / b
a /= b

a = a % b
a %= b
==    	
!=	
>		
<		
>=	
<=

關係運算子

可以對int, float, string比大小

is

is not

x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is z)

# returns True 

print(x is y)

# returns False 

print(x == y)

# returns True
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is not z)

# returns False 

print(x is not y)

# returns True 
print(x != y)

# returns False

in

x = ["apple", "banana"]

print("banana" in x)
# True

not in

x = ["apple", "banana"]

print("pineapple" not in x)
# True

邏輯運算子

a = 3
b = 2
c = 1

print(a > b and b > c)    # True
print(a > c or c > b)    # True
print(not a > b)    # False

位元運算(bitwise)

warning:有難度!

轉成二進位!

\(7_{(2)}\)=\(111_{(2)}\)

1 1 1

\(2^0\)

\(2^1\)

\(2^2\)

example:

\(11_{(10)}\)=\(1011_{(2)}\)

\(5_{(10)}\)=\(101_{(2)}\)

二進位下做

類似加減乘除的事

用真值表來執行
一個一個位元來做!

(位元就像個位十位百位)

bitwise and

a=a&b
AND 1 0
1 1 0
0 0 0

真值表

ex.5&3=1

第一個 1 0 1
第二個 0 1 1
結果 0 0 1

二進位:

都是1的時候1
其他0

bitwise or

a=a|b
AND 1 0
1 1 1
0 1 0

真值表

ex.5\(|\)3=7

第一個 1 0 1
第二個 0 1 1
結果 1 1 1

二進位:

其中至少一個1的時候1
其他0

bitwise xor

a=a^b
AND 1 0
1 0 1
0 1 0

真值表

ex.5^3=6

第一個 1 0 1
第二個 0 1 1
結果 1 1 0

二進位:

一樣的時候0
其他1

bitwise not(取反)

a=~a
NOT
1 0
0 1

真值表

ex.~5

第一個 1 0 1
結果 0 1 0

二進位:

bitwise 左移

a=(a<<1)

ex.5<<1

第一個 0 1 0 1
結果 1 0 1 0

二進位:

左移

bitwise 右移

a=(a>>1)

ex.5>>1

第二個 1 0 1
結果 0 1 0

二進位:

if else

如果 條件1成立:

    做某件事

否則 如果 條件2成立 :

   做另一件事

...

否則

  以上條件都不成立做這件事

if name == "Jerry":
    print("dolphin knight")
elif name == "Eason":
    print("yennnn")
else:
    print("Who are you?")
if name == "Jerry":
    print("dolphin knight")
elif name == "Eason":
    print("yennnn")
else:
    print("Who are you?")
  • if  elif  else 後面要加  ' : '
  • 用縮排分隔程式區塊
  • 必須有一個if,且僅有一個
  • 可以有任意個elif,也可以沒有
  • 可以有0個或1個else
if a>b:
 print("ORZ")
if a>=b:
 print("ORZ")
if a<b:
 print("ORZ")
if a<=b:
 print("ORZ")
if a!=b:
 print("ORZ")
if a==b:
 print("ORZ")
if a!=b and a>b:
  print("ORZ")
  
if a!=b or a>b:
  print("ORZ")
  
if a!=b:
  print("O")
else :
  print("R")
  
if a!=b:
  print("O")
elif a>b:
  print("R")
else :
  print("Z")

迴圈

迴圈

  • 重複做一些事情
  • while
  • for

while

while 條件成立 :

    做一些事情

hard = 0
while hard < 100: 
  print("I am listening")
  hard += 1

while 後面加 ' : '

用縮排分隔程式區塊

for

for 變數 in 序列 :

    做一些事情

  • for會從頭到尾遍歷序列的每個元素
  • 序列可以是tuple, list, range, dict, set, string, ....
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

for 後面加 ' : '

用縮排分隔程式區塊

sum = 0
for x in range(5, 10, 2):
  sum += x
print(sum)    # 21

for迴圈常常也會搭配 range 服用

迴圈控制

break

continue

else

break

  • 跳出整個迴圈
  • for 和 while 都可以用
  • 常常搭配if服用
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break
    
# apple
# banana

continue

  • 跳過這次迴圈
  • for 和 while 都可以用
  • 常常搭配if服用
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)
  
# apple
# cherry

else

  • 完整執行完迴圈沒有被break掉的時候執行
  • for 和 while 都可以用
for x in range(6):
  if x == 3: break
  print(x)
else:
  print("Finally finished!")

function

def my_function():
  print("Hello from a function")

my_function()

Function宣告

  • 用def 宣告一個function
  • def後面加 :
  • 用縮排分隔程式區塊
def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

傳參數

def func(a,b):
  if a<10:
    print(b)
    func(a+1,b)
  a+=1

func(1,"7122")
def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")
def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
def my_function(**kid):
  print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")
def my_function(x):
  return 5 * x

print(my_function(3))
def myfunction():
  pass

Object

物件

Object

  • 一個把資料和函式包裝在一起的結構
  • 保護資料不會被隨意修改
  • 開發大型專案好用
  • 其實Python的每個變數都是物件 ( !

Object

Data

Function

Function

類別 v.s. 物件

  • 類別是物件的模板
  • 物件是類別的實體
  • 類別:class
  • 物件:object
  • 類別定義了物件的功能、內容
  • 物件是你可以存取、真的在做事的東西

建立類別

import math


class point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

    def getx(self):
        return self._x

    def gety(self):
        return self._y

    def print(self):
        print("({}, {})".format(self._x, self._y))
        return

    def dist(self, point2):
        # distance
        return math.sqrt((self._x - point2.getx()) ** 2 + (self._y - point2.gety()) ** 2)

    def move(self, dx, dy):
        return point(self._x + dx, self._y + dy)
A = point(3, 4)
print(A.getx(), A.gety(), sep=',')

B = A.move(5, 12)
B.print()

d = A.dist(B)
print(d)

宣告與存取物件

.

(承上頁的扣的)

Lambda

不用名字的function

lambda arguments : expression

基本形式:

好處:少一個變數、縮短程式碼

x = lambda a : a
print(x(5))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

好的用法:

def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

常用function

math

不需引入的函數

max(取最大值)

min(取最小值)

x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)

#result: 5
#25

pow(a,b)=\(a^b\)

x = pow(4, 3)

print(x)

#result: 64

abs(a)=\(|a|\)

x = -1
print(x)
x=abs(x)
print(x)

#result: -1
#1

需要引入的函數

import math

sqrt(a)=\( \sqrt{a}\)

import math

a=2
print(math.sqrt(a))

#result: 1.4142135623730951

ceil(a)=\(\lceil a\rceil\)

floor(a)=\(\lfloor a\rfloor\)

import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1

備註:

\(\lceil a\rceil\)上高斯

\(\lfloor a\rfloor\) 下高斯

\(\pi\)

import math

x = math.pi

print(x)

#result: 3.141592653589793

本簡報改編自

kumokunn的slides

reference:

四校聯課-Python

By yennnn

四校聯課-Python

建楓成景四校聯課《404不存在的聯課》 - Python 爬蟲 Part.1

  • 373