Skip to content

[Python] 基本入門語法概覽

Python 是個簡單優美的語言,我在發這篇之前斷斷續續寫過 Python 的基本教學:《Python 基本教學系列》。大致上分成 15 個章節,紀錄著 Python 之間大大小小可能應該要學習的功能。今天,我將會紀錄該如何快速地學習 Python。時間嘛,我想大該就抓個一小時吧!

我一直以來都很喜歡『詳細』的東西。當初的教學文受限於時間、精力,只能分成十幾篇斷斷續續地寫著,今天就要把精華的部份挑出來,濃縮成一篇簡短有力的教學文。

如果想參閱官方的文件,你可以參考這裡: https://docs.python.org/3.6/contents.html

廢話不多說,我們直接開始吧!


為什麼該學 Python ?

Python 是現在最紅的程式語言之一,並且擁有著眾多的套件可以完成各式各樣的功能。

Python Ranking

況且 Python 是現在機器學習、深度學習框架的主流語言,學習 Python 的投資報酬率非常地高。


下載、安裝 Python

首先,我們來安裝 Python。我推薦使用 Python 3.6 ,基本上 Python 各版本之間並沒有什麼太大的差異,但 Python 3.6 在許多機器學習的框架上運行地比較順利。

首先來到 Python 官網下載的地方,依照你的作業系統進行下載:https://www.python.org/downloads/release/python-368/

下載好之後執行安裝檔,一直選擇 Next,就會安裝在電腦裡了。如果不只想要原生的 Python IDLE 來寫程式,也可以考慮安裝 Jupyter notebook 或是 PyCharm:《Python IDE PyCharm 安裝教學》

安裝好之後,我們便可以開始寫程式啦。


印出 Hello World

print('Hello World!')



Output:

Hello World!

print() 便是 Python 印出東西的指令。


加減乘除

print(2+2)
print(50-6)
print(7*7)
print(8/2)



Output:

4
44
49
4.0

處理加減乘除符號非常直覺。 4.0 的那項資料型態為 float,其餘皆為 int。


變數

變數為可以將數值、文字儲存下來的載體,方便我們進行後續的各種處理。

text = 'Hello'
number = 7
print(text)
print(number)



Output:

Hello
7

For 迴圈

for 迴圈為可以反覆執行我們指令的程式區塊,範例如下:

for n in range(10):
    print(n)



Output:

0
1
2
3
4
5
6
7
8
9

for n in range(10) 代表 n 值從 0 到 9 都執行了一次。底下『縮排』的部份則是我們 for 迴圈要執行的部份。


While 無限迴圈

While 迴圈就像是沒有設定範圍的 for 迴圈,當然,你要設定也是可以的。 while 後方接的是『執行條件』,若是設定為 True 便會一直執行下去。

n = 0
while True:
    n += 1
    print(n)

    if n == 10:
        break



Output:

1
2
3
4
5
6
7
8
9
10

這裡設定 n 等於 10 時結束 while 迴圈,後面會介紹的 if 條件判斷式以及流程控制。


If 條件判斷式

for n in range(1, 10):
    if n % 3 == 0:
        print(n, 'Divided by 3')
    elif n % 3 == 1:
        print(n, 'After being divided by 3, the remaining 1')
    else:
        print(n, 'After being divided by 3, the remaining 2')



Output:

 1 After being divided by 3, the remaining 1
 2 After being divided by 3, the remaining 2
 3 Divided by 3
 4 After being divided by 3, the remaining 1
 5 After being divided by 3, the remaining 2
 6 Divided by 3
 7 After being divided by 3, the remaining 1
 8 After being divided by 3, the remaining 2
 9 Divided by 3 

只要符合 if 後面的條件,便會自動執行底下縮排的程式碼。

elif 為第二個條件判斷,只要不符合 if 便會開始由第二個 elif 判斷條件,依序往下,只要其中一個 elif 符合條件便會執行。

else 則是所有以上條件皆不符合時,執行底下縮排的部份。


流程控制

流程控制的指令基本上分為 breakpasscontinue 等三類。

break 上面已經有範例了,為跳出迴圈的指令。

for n in range(10):
    if n == 4:
        pass
    else:
        print(n)



Output:

1
2
3
5
6
7
8
9

pass 基本上為填充用途,就是在符合這個條件時不執行程式碼。迴圈底下若還有其他程式,還是會繼續執行。

continue 的話則是會徹底跳過這次迴圈。

# Continue
times = 0
for n in range(10):
    if n == 4:
        continue
    else:
        print(n)

    times += 1
    print('we run %d times' % times)



Output:

 0
we run 1 times
1
we run 2 times
2
we run 3 times
3
we run 4 times
5
we run 5 times
6
we run 6 times
7
we run 7 times
8
we run 8 times
9
we run 9 times

可以看到第五次 (也就是印出 4 的時候) 的程式直接被中斷了,沒有計算為一次執行程式。這就是由於 continue 直接跳過了某次迴圈。


Bool 布林值

Python 當中的布林值可以直接表為 TrueFalse,也可以表示為 1 和 0。


邏輯符號

  • 大於 >
  • 小於 <
  • 等於 ==
  • 大於等於 >=
  • 小於等於 <=
  • 不等於 !=

函式 function

我們可以使用 def 來定應程式當中的函式,方便我們模組化我們的程式,並且會重複使用的部份可以直接定義起來重複調用。

def fibo(n):
    if n == 0: return 0;
    elif n == 1: return 1;
    return fibo(n-1) + fibo(n-2)



以上的簡單的 Fibonacci 程式,我們可以簡單地嘗試一下效果。

ans = fibo(5)
print(ans)



Output:

5

n 值即為我們可以輸入函式的數值。隨著不同的輸入,會產生不一樣的輸出。


List 列表

List 可以直接設定不同資料型態的數值在 List 內,並且可以使用 for 迴圈讀出。

List = [1, 2, 3, 'Today', 'is', 'nice.']
for value in List:
    print(value)



Output:

1
2
3
Today
is
nice.

可以使用 append() 來新增元素、使用 remove() 來移除元素。

List.append('New')
print('Append:', List)

List.remove('New')
print('Remove:', List)



Output:

Append: [1, 2, 3, 'Today', 'is', 'nice.', 'New']
Remove: [1, 2, 3, 'Today', 'is', 'nice.']

Tuple

Tuple 常被譯為『元組』,將資料存入 tuple 之後便沒辦法再新增元素了。

a = (1, 2, 2, 3, 3, 3, 'a', 'b', 'c', 'c')
print(a.count(2))
print(a.count(3))
print(a.index(1))
print(a.index('a'))



Output:

2
3
0
6

a.count(n) 可以計算 tuple 中共有多少元素 n
a.index(n) 可以計算 n 的位置


Set

Set 這種資料型態沒辦法儲存相同的值,並且可以計算兩個 set 的『交集』、『聯集』、『差集』。

a = set([1, 2, 3, 'a', 'b', 'c'])
b = set([1, 3, 5, 'a', 'c', 'e'])
print('Intersection:', a.intersection(b))
print('Union:', a.union(b))
print('Difference:', a.difference(b))



Output:

Intersection: {'c', 1, 'a', 3}
Union: {'b', 1, 2, 3, 'a', 'e', 5, 'c'}
Difference: {'b', 2}

Dictionary

Dictionary 就是 key-value 對應的資料型態,可以用於快速的建表。

b = dict()

b[1] = 2
b[2] = 4
b[3] = 6

print(b[1])
print(b[2])
print(b[3])



Output:

2
4
6

Import

想要使用別人寫好的套件、甚至是使用 Python 原生的套件,都必須使用 import 來匯入指定的模組。

以下以時間處理的 time 舉例:

import time
time.sleep(3)

from time import sleep
sleep(3)



time.sleep(n) 便是讓系統停住 n 秒的功能;另外,如果只是用想調用 sleep() 函式,也可以直接使用 from ... import xxx 這樣的方法來匯入。


錯誤處理

在 Python 當中,我們可以使用 tryexcept 來進行簡單的錯誤處理。

try:
    hello()
except:
    print('Error!')



Output:

Error!

首先,我們並沒有定義 hello() 這個函式,所以在 try 底下執行的時候便發生錯誤了。然後,若是在 try 底下發生了錯誤,程式便會自動開始執行 except 底下的程式。

這樣就可以確保我們即使程式發生問題,也不至於讓程式突然中斷了。我們可以透過事先進行錯誤處理,來讓程式採取不一樣的處理模式來規避問題。


檔案讀寫

Python 中,通常是使用 open() 指令來打開檔案。至於打開檔案,最常用的其實便是『r』、『w』、『a』這三種模式。

假設我有個這樣的文本,有著以下的內容:

Today is a nice day!

然後我存檔,檔名叫做 test.txt。

text = open('test.txt', 'r', encoding='utf-8').read()
print(text)



Output:

Today is a nice day!

我們第一個指定的便是檔案名、其次是打開的模式,最後是我們文字編碼的型態。在 Python 中,現在一律要用 utf-8 來處理比較不會有問題。

r 是單純地讀取。


newText = 'Today is not a nice day!'
open('test.txt', 'w', encoding='utf-8').write(newText)

text = open('test.txt', 'r', encoding='utf-8').read()
print(text)



Output:

Today is not a nice day!

w 是寫入,注意,這會取代當前文本中所有的內容。若是我們指定的檔案並不存在,會重新創建這個檔案。


newText = '\nToday is a nice day!'
open('test.txt', 'a', encoding='utf-8').write(newText)

text = open('test.txt', 'r', encoding='utf-8').read()
print(text)



Output:

Today is not a nice day!
Today is a nice day!

a 模式是續寫,會繼續在文件底下寫入文本,不會覆蓋原本內容。’\n’ 是換行符號。


Class

Class 是 Python 中物件導向的寫法,基本的寫法如下。

class Human():
    def __init__(self, name, age):
        self.name = name
        self.age = age


if __name__ == '__main__':
    clay = Human('Clay', 25)
    print('Name:', clay.name)
    print('Age:', clay.age)


Output:

Name: Clay
Age: 25

class 指令後面接著我們要創立的類別的名稱,在這裡我們創立了 Human 這個類別。

__init__ 為初始化的區塊,每當這個 class 作為物件被建立時, __init__ 的部份會自動執行。

在這裡,第一次建立 Human 這個類別時,就必須把『名字』和『年齡』都一併輸入。

另外,在 class 當中我們可以創立這個 class 專屬的 method,使用 def self.xxx 便可以建立。建立起的 method 只有這個 class 能夠調用。


以上,一小時的 Python 教學 Speed Run 就結束了!我粗估是覺得時間應該差不多,不過這種寫作者自己的感想當然是不準的,沒有什麼參考性。

如果你花的時間比一小時還少,那麼恭喜你,至少看起來 Python 基本的語法難不倒你。

如果你花的時間比一小時還多,那也別在意。可能你需要時間慢慢測試上方那些 sample code,亦或者你是個比較仔細的人 —— 甚至根本就是我搞錯了讀這些筆記的時間。

總之,希望大家都能在 Coding 當中找到樂趣

Leave a Reply