天天看點

Python基礎入門篇(上)1 基本資料類型2 容器資料類型3 條件語句&疊代循環4 總結

1 基本資料類型

Python 裡面有自己的内置資料類型 (build-in data type),基本資料類型包含三種,分别是整型 (int),浮點型 (float),和布爾型 (bool)

1.1 整型

整數 (integer) 是最簡單的資料類型,和下面浮點數的差別就是前者小數點後沒有值,後者小數點後有值。

a = 205
print(a, type(a))
           
205 <class 'int'>
           

通過 print 的可看出 a 的值,以及類 (class) 是 int。Python 裡面萬物皆對象(object),「整數」也不例外,隻要是對象,就有相應的屬性 (attributes) 和方法 (methods)。

知識點:

  • 通過 dir( X ) 和help( X ) 可看出 X 對應的對象裡可用的屬性和方法。
    • X 是 int,那麼就是 int 的屬性和方法
    • X 是 float,那麼就是 float 的屬性和方法
['__abs__',
 '__add__',
 '__and__',
 '__bool__',
 '__ceil__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__index__',
 '__init__',
 '__init_subclass__',
 '__int__',
 '__invert__',
 '__le__',
 '__lshift__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__round__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__trunc__',
 '__xor__',
 'bit_length',
 'conjugate',
 'denominator',
 'from_bytes',
 'imag',
 'numerator',
 'real',
 'to_bytes']
           

1.2 浮點數

簡單來說,浮點型 (float) 數就是實數。

print(1, type(1))
print(1.0, type(1.0))
           
1 <class 'int'>
1.0 <class 'float'>
           

加一個小數點"." 就可以建立 float。有時候我們想保留浮點型的小數點後 n 位。可以用 decimal 包裡的 Decimal 對象和 getcontext() 方法來實作

import decimal
from decimal import Decimal
           

Python 裡面有很多用途廣泛的包 (package),用什麼你就引進 (import) 什麼。包也是對象,也可以用上面提到的dir(decimal) 來看其屬性和方法。比如 getcontext() 顯示了 Decimal 對象的預設精度值是 28 位 (prec=28)。

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
           
d = Decimal(1) / Decimal(3) # 預設保留小數後面28位
d
           
Decimal('0.3333333333333333333333333333')
           
#如果要保留 4 位,需要用 getcontext().prec 來調整精度
decimal.getcontext().prec = 4
e = Decimal(1)/Decimal(3)
e
           
Decimal('0.3333')
           
# 高精度的 float 加上低精度的 float,保持了高精度
d + e
           
Decimal('0.6666333333333333333333333333')
           

1.3 布爾型

布爾 (boolean) 型變量隻能取兩個值,True 和 False。當把布爾變量用在數字運算中,用 1 和 0 代表 True 和 False。

T = True
F = False
print(T + 2)
print(F - 8)
           
3
-8
           
  • 除了直接給變量指派 True 和 False,還可以用 bool(X) 來建立變量,其中 X 可以是
    • 基本資料類型:整型,浮點型、布爾型
    • 容器資料類型:字元,元組,清單,字典和集合
print( type(0), bool(0), bool(1) )
print( type(10.31), bool(0.00), bool(10.31) )
print( type(True), bool(False), bool(True) )
           
<class 'int'> False True
<class 'float'> False True
<class 'bool'> False True
           

bool 作用在基本類型變量的總結:X 隻要不是整型 0、浮點型 0.0,bool(X) 就是 True,其餘就是 False。

print( type(''), bool( '' ), bool( 'python' ) )
print( type(()), bool( () ), bool( (10,) ) )
print( type([]), bool( [] ), bool( [1,2] ) )
print( type({}), bool( {} ), bool( {'a':1, 'b':2} ) )
print( type(set()), bool( set() ), bool( {1,2} ) )
           
<class 'str'> False True
<class 'tuple'> False True
<class 'list'> False True
<class 'dict'> False True
<class 'set'> False True
           

bool 作用在容器類型變量的總結:X 隻要不是空的變量,bool(X) 就是 True,其餘就是 False。

知識點:

  • 确定bool(X) 的值是 True 還是 False,就看 X 是不是空,空的話就是 False,不空的話就是 True。
    • 對于數值變量,0, 0.0 都可認為是空的。
    • 對于容器變量,裡面沒元素就是空的。

2 容器資料類型

整型、浮點型和布爾型都可以看成是單獨資料,而這些資料都可以放在一個容器裡得到一個「容器類型」的資料,比如:

  • 字元 (str) 是一容器的位元組 char,注意 Python 裡面沒有 char 類型的資料,可以把單字元的 str 當做 char。
  • 元組 (tuple)、清單 (list)、字典 (dict) 和集合 (set) 是一容器的任何類型變量。

2.1 字元

字元用于處理文本 (text) 資料,用「單引号 ’」和「雙引号 “」來定義都可以。

t1 = 'i love Python!'
print( t1, type(t1) )
t2 = "I love Python!"
print( t2, type(t2) )
           
i love Python! <class 'str'>
I love Python! <class 'str'>
           
  • 字元中常見的内置方法 (可以用 dir(str) 來查) 有
    • capitalize():大寫句首的字母
    • split():把句子分成單詞
    • find(x):找到給定詞 x 在句中的索引,找不到傳回 -1
    • replace(x, y):把句中 x 替代成 y
    • strip(x):删除句首或句末含 x 的部分
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isascii',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']
           
'I love python!'
           
['I', 'love', 'Python!']
           
2
           
-1
           
'I like R!'
           
print( 'http://www.python.org'.strip('htp:/'))
print( 'http://www.python.org'.strip('.org'))
           
www.python.org
http://www.python
           

索引和切片

s = 'Python'
print( s )
print( s[2:4] )
print( s[-5:-2] )
print( s[2] )
print( s[-1] )
           
Python
th
yth
t
n
           

Python 裡面索引有三個特點 (經常讓人困惑):

  • 從 0 開始 (和 C 一樣),不像 Matlab 從 1 開始。
  • 切片通常寫成 start:end 這種形式,包括「start 索引」對應的元素,不包括「end索引」對應的元素。是以 s[2:4] 隻擷取字元串第 3 個到第 4 個元素。
  • 索引值可正可負,正索引從 0 開始,從左往右;負索引從 -1 開始,從右往左。使用負數索引時,會從最後一個元素開始計數。最後一個元素的位置編号是 -1。
    Python基礎入門篇(上)1 基本資料類型2 容器資料類型3 條件語句&amp;疊代循環4 總結

與其把注意力放在元素對應的索引,不如想象将元素分開的隔欄,顯然 6 個元素需要 7 個隔欄,隔欄索引也是從 0 開始,這樣再看到 start:end 就認為是隔欄索引,那麼擷取的元素就是「隔欄 start」和「隔欄 end」之間包含的元素。如上圖:

  • string[2:4] 就是「隔欄 2」和「隔欄 4」之間包含的元素,即 th
  • string[-5:-2] 就是「隔欄 -5」和「隔欄 -2」之間包含的元素,即 yth

正規表達式

  • 正規表達式 (regular expression) 主要用于識别字元串中符合某種模式的部分。
input = """
'06/18/2019 13:00:00', 100, '1st';
'06/18/2019 13:30:00', 110, '2nd';
'06/18/2019 14:00:00', 120, '3rd'
"""
input
           
"\n'06/18/2019 13:00:00', 100, '1st';\n'06/18/2019 13:30:00', 110, '2nd';\n'06/18/2019 14:00:00', 120, '3rd'\n"
           
import re
pattern = re.compile("'[0-9/:\s]+'")
           
["'06/18/2019 13:00:00'", "'06/18/2019 13:30:00'", "'06/18/2019 14:00:00'"]
           
  • 最外面的兩個單引号 ’ 代表該模式以它們開始和結束
  • 中括号 [] 用來概括該模式涵蓋的所有類型的位元組
  • 0-9 代表數字類的位元組
  • / 代表正斜線
  • : 代表分号
  • \s 代表空格
  • [] 外面的加号 + 代表 [] 裡面的位元組出現至少 1 次

2.2 元組

元組」定義文法為 :(元素1, 元素2, …, 元素n)

  • 關鍵點是「小括号 ()」和「逗号 ,」
    • 小括号把所有元素綁在一起
    • 逗号将每個元素一一分開
t1 = (1, 10.31, 'python')
t2 = 1, 10.31, 'python'
print( t1, type(t1) )
print( t2, type(t2) )
           
(1, 10.31, 'python') <class 'tuple'>
(1, 10.31, 'python') <class 'tuple'>
           
# 建立二維元組
nested = (1, 10.31, 'python'), ('data', 11)
nested
           
((1, 10.31, 'python'), ('data', 11))
           

索引和切片

元組中可以用整數來對它進行索引 (indexing) 和切片 (slicing)。一般來說,前者是擷取單個元素,後者是擷取一組元素。

print(nested[0])
print( nested[0][0], nested[0][1], nested[0][2] )
           
(1, 10.31, 'python')
1 10.31 python
           
(1, 10.31)
           
(1,)
           

元組有不可更改 (immutable) 的性質,是以不能直接給元組的元素指派.

t = ('OK', [1, 2], True)
t[2] = False
           
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-60-2391723ab1a0> in <module>
      1 t = ('OK', [1, 2], True)
----> 2 t[2] = False


TypeError: 'tuple' object does not support item assignment
           

但是隻要元組中的元素可更改 (mutable),那麼我們可以直接更改其元素,注意這跟指派其元素不同。

t[1].append(3)
t
           

内置方法

元組大小和内容都不可更改,是以隻有 count 和 index 兩種方法。

t = (1, 10.31, 'python')
print( t.count('python') ) # 統計出現次數
print( t.index(10.31) ) # 傳回元素在元組中的位置
           
  • count(‘python’) 是記錄在元組 t 中該元素出現幾次,顯然是 1 次
  • index(10.31) 是找到該元素在元組 t 的索引,顯然是 1

元組拼接

元組拼接 (concatenate) 有兩種方式,用「加号 +」和「乘号 *」,前者首尾拼接,後者複制拼接。

解壓元組

# 解壓一維元組
t = (1, 10.31, 'python')
(a, b, c) = t
print( a, b, c )
           
# 解壓二維元組
t = (1, 10.31, ('OK','python'))
(a, b, (c,d)) = t
print( a, b, c, d )
           
1 10.31 OK python
           
# 如果隻想要元組其中幾個元素,用通配符「*」,英文叫 wildcard,在計算機語言中代表一個或多個元素。
t = 1, 2, 3, 4, 5
a, b, *rest, c = t
print( a, b, c )
print( rest )
           
1 2 5
[3, 4]
           
# 如果根本不在乎 rest 變量,那麼就用通配符「*」加上下劃線「_」
a, b, *_ = t
print( a, b )
           
1 2
           
  • 優缺點
    • 優點:占記憶體小,安全,建立周遊速度比清單快,可一賦多值。
    • 缺點:不能添加和更改元素。

2.3 清單

「清單」定義文法為 [元素1, 元素2, …, 元素n]

  • 關鍵點是「中括号 []」和「逗号 ,」
    • 中括号把所有元素綁在一起
    • 逗号将每個元素一一分開
l = [1, 10.31,'python']
print(l, type(l))
           
[1, 10.31, 'python'] <class 'list'>
           

内置方法

不像元組,清單内容可更改 (mutable),是以附加 (append, extend)、插入 (insert)、删除 (remove, pop) 這些操作都可以用在它身上。

l.append([4, 3])
print( l )
l.extend([1.5, 2.0, 'OK'])
print( l ) 
           
[1, 10.31, 'python', [4, 3]]
[1, 10.31, 'python', [4, 3], 1.5, 2.0, 'OK']
           
  • append 是追加,把一個東西整體添加在清單後;
  • extend 是擴充,把一個東西裡的所有元素添加在清單後。
# 插入
l.insert(1, 'abc') # 1表示在索引為1的元素前面插入
print(l)
           
[1, 'abc', 10.31, 'python', [4, 3], 1.5, 2.0, 'OK']
           
# 删除
l.remove('python') # remove first occurrence of object
print(l)
           
[1, 'abc', 10.31, [4, 3], 1.5, 2.0, 'OK']
           
p = l.pop(3) # 從清單在去掉索引為3的元素,并傳回這個元素
print( p )
print( l ) 
           
[4, 3]
[1, 'abc', 10.31, 1.5, 2.0, 'OK']
           
  • remove是指定具體要删除的元素,比如 ‘python’
  • pop是指定一個編号位置,比如 3,删除 l[3] 并傳回出來.

索引和切片

l = [7, 2, 9, 10, 1, 3, 7, 2, 0, 1]
l[1:5]
           
[2, 9, 10, 1]
           
[7, 2, 0, 1]
           
l[2:4] = [999, 10000]
l
           
[7, 2, 999, 10000, 1, 3, 7, 2, 0, 1]
           
  • 切片的通用寫法是:
    • start : stop : step
# 情況1:start
print( l )
print( l[3:] )
print( l[-4:] )
           
[7, 2, 999, 10000, 1, 3, 7, 2, 0, 1]
[10000, 1, 3, 7, 2, 0, 1]
[7, 2, 0, 1]
           
# 情況2:stop
print( l )
print( l[:6] )
print( l[:-4] )
           
[7, 2, 999, 10000, 1, 3, 7, 2, 0, 1]
[7, 2, 999, 10000, 1, 3]
[7, 2, 999, 10000, 1, 3]
           
# 情況3:start:stop
print( l )
print( l[2:4] )
print( l[-5:-1] )
           
[7, 2, 999, 10000, 1, 3, 7, 2, 0, 1]
[999, 10000]
[3, 7, 2, 0]
           
# 情況4:start:stop;step

print( l )
print( l[1:5:2] )
print( l[:5:2] )
print( l[1::2] )
print( l[::2] )
print( l[::-1] )
           
[7, 2, 999, 10000, 1, 3, 7, 2, 0, 1]
[2, 10000]
[7, 999, 1]
[2, 10000, 3, 2, 1]
[7, 999, 1, 7, 0]
[1, 0, 2, 7, 3, 1, 10000, 999, 2, 7]
           

以具體的 step 從編号 start 往編号 stop 切片。注意最後把 step 設為 -1,相當于将清單反向排列。

清單拼接

清單拼接也有兩種方式,用「加号 +」和「乘号 *」,前者首尾拼接,後者複制拼接。

[1, 10.31, 'python', 'data', 11, 'OK']
           
[1, 10.31, 'python', 1, 10.31, 'python']
           
  • 優缺點
    • 優點:靈活好用,可索引、可切片、可更改、可附加、可插入、可删除。
    • 缺點:相比 tuple 建立和周遊速度慢,占記憶體。此外查找和插入時間較慢。

2.4 字典

  • 「字典」定義文法為:{元素1, 元素2, …, 元素n},其中每一個元素是一個「鍵值對」—— 鍵:值 (key:value)
  • 關鍵點是「大括号 {}」,「逗号 ,」和「分号 :」
    • 大括号把所有元素綁在一起
    • 逗号将每個鍵值對一一分開
    • 分号将鍵和值分開
d = {
'Name' : 'Tencent',
'Country' : 'China',
'Industry' : 'Technology',
'Code': '00700.HK',
'Price' : '361 HKD'
}
print( d, type(d) )
           
{'Name': 'Tencent', 'Country': 'China', 'Industry': 'Technology', 'Code': '00700.HK', 'Price': '361 HKD'} <class 'dict'>
           

内置方法

字典裡最常用的三個内置方法就是 keys(), values() 和 items(),分别是擷取字典的鍵、值、對。

print( list(d.keys()),'\n' )
print( list(d.values()), '\n' )
print( list(d.items()) )
           
['Name', 'Country', 'Industry', 'Code', 'Price'] 

['Tencent', 'China', 'Technology', '00700.HK', '361 HKD'] 

[('Name', 'Tencent'), ('Country', 'China'), ('Industry', 'Technology'), ('Code', '00700.HK'), ('Price', '361 HKD')]
           
# 添加
d['Headquarter'] = 'Shen Zhen'
d
           
{'Name': 'Tencent',
 'Country': 'China',
 'Industry': 'Technology',
 'Code': '00700.HK',
 'Price': '361 HKD',
 'Headquarter': 'Shen Zhen'}
           
# 擷取
print( d['Price'] )
print( d.get('Price') )
           
361 HKD
361 HKD
           
# 更新(指派)
d['Price'] = '359 HKD'
d
           
{'Name': 'Tencent',
 'Country': 'China',
 'Industry': 'Technology',
 'Code': '00700.HK',
 'Price': '359 HKD',
 'Headquarter': 'Shen Zhen'}
           
# 删除
del d['Code']
d
           
{'Name': 'Tencent',
 'Country': 'China',
 'Industry': 'Technology',
 'Price': '359 HKD',
 'Headquarter': 'Shen Zhen'}
           
#  pop() 函數
print( d.pop('Industry') )
d
           
Technology





{'Name': 'Tencent',
 'Country': 'China',
 'Price': '359 HKD',
 'Headquarter': 'Shen Zhen'}
           

不可更改鍵

  • 字典裡的鍵是不可更改的,是以隻有那些不可更改的資料類型才能當鍵,比如整數、浮點數、布爾、字元、元組,而清單卻不行,因為它可更改。
d = {
2 : 'integer key',
10.31 : 'float key',
True  : 'boolean key',
('OK',3) : 'tuple key'
}
d
           
{2: 'integer key',
 10.31: 'float key',
 True: 'boolean key',
 ('OK', 3): 'tuple key'}
           
# True 其實和整數 1 是一樣的,由于鍵不能重複,當你把 2 該成 1時,字典隻會取其中一個鍵。
d = {
1 : 'integer key',
10.31 : 'float key',
True : 'boolean key',
('OK',3) : 'tuple key'
}
d
           
{1: 'boolean key', 10.31: 'float key', ('OK', 3): 'tuple key'}
           
  • 如何快速判斷一個資料類型 X 是不是可更改的呢?
    • 麻煩方法:用 id(X) 函數,對 X 進行某種操作,比較操作前後的 id,如果不一樣,則 X 不可更改,如果一樣,則 X 可更改。
    • 便捷方法:用 hash(X),隻要不報錯,證明 X 可被哈希,即不可更改,反過來不可被哈希,即可更改。
i = 1
print( id(i) )
i = i + 2
print( id(i) )
# 整數 i 在加 1 之後的 id 和之前不一樣,是以加完之後的這個 i (雖然名字沒變),但是不是加前的那個 i 了,是以整數是不可更改的。
           
140735306904400
140735306904464
           
l = [1, 2]
print( id(l) )
l.append('Python')
print( id(l) )
#清單 l 在附加 'Python' 之後的 id 和之前一樣,是以清單是可更改的。
           
2101930268040
2101930268040
           
-5978476979602947836
           
1852668959836117693
           
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-91-54c2881f2699> in <module>
----> 1 hash( [1,2,'Python'] )


TypeError: unhashable type: 'list'
           

字元 s 和元組 t 都能被哈希,是以它們是不可更改的。清單 l 不能被哈希,是以它是可更改的。

  • 優缺點
    • 優點:查找和插入速度快
    • 缺點:占記憶體大

2.5 集合

建立集合

「集合」有兩種定義文法

  • 第一種是:{元素1, 元素2, …, 元素n},關鍵點是「大括号 {}」和「逗号 ,」
    • 大括号把所有元素綁在一起
    • 逗号将每個元素一一分開
  • 第二種是用 set() 函數,把清單或元組轉換成集合。
# set( 清單 或 元組 )
A = set(['u', 'd', 'ud', 'du', 'd', 'du']) # 清單
B = {'d', 'dd', 'uu', 'u'} # 元組
print( A )
print( B )
           
{'u', 'du', 'ud', 'd'}
{'d', 'dd', 'u', 'uu'}
           

從 A 的結果發現集合的兩個特點:

  • 無序 (unordered)
  • 唯一 (unique)

由于 set 存儲的是無序集合,是以沒法通過索引來通路,但是可以判斷一個元素是否在集合中。

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-93-ee721d8948fe> in <module>
----> 1 B[1]


TypeError: 'set' object does not support indexing
           
'u' in B
           
True
           

内置方法

用 set 的内置方法就把它當成是數學上的集,那麼并集、交集、差集都可以使用。

  • 并集:union()
  • 交集:intersection()
  • 差集:difference()
  • 對稱差集:symmetric_difference()
# 并集 OR
print( A.union(B) )     # All unique elements in A or B
print( A | B )          # A OR B
           
{'du', 'ud', 'u', 'dd', 'd', 'uu'}
{'du', 'ud', 'u', 'dd', 'd', 'uu'}
           
# 交集 AND
print( A.intersection(B) )   # All elements in both A and B
print( A & B )               # A AND B
           
{'d', 'u'}
{'d', 'u'}
           
# 差集 A - B
print( A.difference(B) )     # Elements in A but not in B
print( A - B )               # A MINUS B
           
{'du', 'ud'}
{'du', 'ud'}
           
# 差集 B - A
print( B.difference(A) )     # Elements in B but not in A
print( B - A )               # B MINUS A
           
{'dd', 'uu'}
{'dd', 'uu'}
           
# 對稱差集XOR
print( A.symmetric_difference(B) )   # All elements in either A or B, but not both
print( A ^ B )                       # A XOR B
           
{'du', 'ud', 'dd', 'uu'}
{'du', 'ud', 'dd', 'uu'}
           
  • 優缺點
    • 優點:不用判斷重複的元素
    • 缺點:不能存儲可變對象

3 條件語句&疊代循環

  • 條件語句 (conditional statement) :在不同條件下完成不同動作
  • 疊代循環 (iterative loop):重複的完成某些動作

3.1 條件語句

條件語句大體有四種格式:

  • if 語句
  • if-else 語句
  • if-elif-else 語句
  • nested 語句
# 給定二進制條件,滿足做事,不滿足不做事。
if x > 0:
    print( 'x is positive' )
           
x is positive
           
# 給定二進制條件,滿足做事 A,不滿足做事 B。
if x % 2 == 0:
    print( 'x is even' )
else :
    print( 'x is odd' )
           
x is odd
           
x = 1
y = 1.0
           
# 給定多元條件,滿足條件 1 做事 A1,滿足條件 2 做事 A2,..., 滿足條件 n 做事 An。直到把所有條件周遊完。
if x < y:
    print( 'x is less than y' )
elif x > y:
    print( 'x is greater than y' )
else:
    print( 'x and y are equal' )
           
x and y are equal
           
'''
給定多元條件,滿足條件 1 做事 A1,不滿足就
    給定多元條件,滿足條件 2 做事 A2,不滿足就
        ...

直到把所有條件周遊完。
'''
if x == y:
    print( 'x and y are equal' )
else:
    if x < y:
        print( 'x is less than y' )
    else:
        print( 'x is greater than y' )
           
x and y are equal
           

3.2 疊代循環

對于疊代循環,Python 裡面有「while 循環」和「for 循環」

# Wihle循環
n = 5
while n > 0:
    print(n)
    n = n-1
print('I love Python')
           
5
4
3
2
1
I love Python
           

While 循環非常簡單,做事直到 while 後面的語句為 False。

# For循環
languages = ['Python', 'R', 'Matlab', 'C++']
for language in languages:
    print( 'I love', language )
print( 'Done!' )
           
I love Python
I love R
I love Matlab
I love C++
Done!
           

Python 裡面的「for 循環」很像讀英文。通用形式的 for loop 如下:

for a in A
    do something with a  
           

其中 for 和 in 是關鍵詞,A 是個可疊代資料 (list, tuple, dic, set),a 是 A 裡面的每個元素

enumerate 函數

enumerate(A) 不僅可以 A 中的元素,還順便給該元素一個索引值 (預設從 0 開始)。此外,用 enumerate(A, j) 還可以确定索引起始值為 j

for i, a in enumerate(A)
    do something with a and i
           
languages = ['Python', 'R', 'Matlab', 'C++']
for i, language in enumerate(languages, 1):
    print( i,',', 'I love', language )
print( 'Done!' )
           
1 , I love Python
2 , I love R
3 , I love Matlab
4 , I love C++
Done!
           

4 總結

學習任何一種都要從最基本開始,基本的東西無外乎“資料類型”、“條件語句”和“遞推循環”。

  1. 資料類型分兩種:
    • 單獨類型:整型、浮點型、布爾型
    • 容器類型:字元、元組、清單、字典、集合

按照 Python 裡「萬物皆對象」的思路,學習每一個對象裡面的屬性 (attributes) 和方法 (methods),你不需要記住所有,有個大概印象有哪些,通過 dir() 來鎖定具體表達式,再去官網上查詢所有細節。這麼學真的很系統而簡單。此外學的時候一定要帶着“它的優缺點是什麼”這樣的問題,所有東西都有 trade-off,一個滿身都是缺點的東西就沒有存在的必要,既然存在肯定有可取之處。

  1. 條件語句 (if, if-else, if-elif-else, nested if) 是為了在不同條件下執行不同操作,
  2. 疊代循環 (while, for) 是重複的完成相同操作。