Python 是一個由 Guido van Rossum 在 1991 年 2 月釋出的程式語言, 發展至今大約過了 20 餘年, 廣泛使用於科學計算、網頁後端開發、系統工具等地方。
Python 這名字是源自於當時 Guido van Rossum 在觀賞的 BBC 喜劇 「Monty Python's Flying Circus」。
[給稍微有經驗的程式設計師]
Python 主要的特性
- 強型別
- 物件導向
- 動態型別
- 直譯式
1+2 # 加法
3
3-4 # 減法
-1
5*6 # 乘法
30
7/8 # 除法
0.875
7//8 # 除法,無條件捨去到個位數
0
10%9 # 取餘數
1
2 ** 10 # 指數
1024
2 ** (1/2) # 開根號
1.4142135623730951
1+2j # 複數 (這裡虛部用 j 表示)
(1+2j)
(1+2j) * (3+4j) # 複數乘法
(-5+10j)
2 ** (1+2j) # 複數指數
(0.36691394948660344+1.9660554808224875j)
abs(-1) # absolute, 絕對值
1
abs(1+2j) # absolute, 絕對值
2.23606797749979
round(3.1415926, 3) # 四捨五入到小數點後第 3 位
3.142
round(3.1415926, 4) # 四捨五入到小數點後第 4 位
3.1416
用 =
來給名字
a = 1
b = 1.5
c = "asd"
type(42) # 用 type 可以得知型別
int
type(3.14159265358979323846)
float
"測試" # str, 字串
'測試'
"""
我
是
多
行
字
串
""" # 用 3 個 " 夾起來
'\n我\n是\n多\n行\n字\n串\n'
'''
我
是
多
行
字
串
''' # 也可以用 3 個 ' 夾起來
'\n我\n是\n多\n行\n字\n串\n'
(42, 'O w O') # tuple, 可以放入各種東西的大箱子,放完後不能更動
(42, 'O w O')
foo = (42, 'O w O')
foo[0] # subscript operator 可以取出其中的值
# 注意,index 從 0 開始算
42
[42, 'O w O'] # list 和 tuple 相似,但放完後可以更動
[42, 'O w O']
結構 (給比較有經驗的人)
{'a': 1, 'b': 42} # dict,冒號左邊的是 key、右邊的是 value,用 key 可以查到 value (想像查字典的狀況)
{'a': 1, 'b': 42}
d = {'a': 1, 'b': 42}
d['b']
42
結構
{1, 2, 3, 3, 3} # set,數學上的集合,裡面的東西不會重複,也沒有順序
{1, 2, 3}
結構
A = {1, 2, 3}
B = {1, 2, 4}
A | B # 取聯集
{1, 2, 3, 4}
A & B # 取交集
{1, 2}
A ^ B # 取對稱差
{3, 4}
A - B # 取差集
{3}
dir(int) # 檢查可以使用的 method
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__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']
help(int) # 看文件上的解說
Help on class int in module builtins: class int(object) | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards zero. | | If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal can be preceded by '+' or '-' and be surrounded | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. | Base 0 means to interpret the base from the string as an integer literal. | >>> int('0b100', base=0) | 4 | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | self != 0 | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floor__(...) | Flooring an Integral returns itself. | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(...) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __round__(...) | Rounding an Integral returns itself. | Rounding with an ndigits argument also returns an integer. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __sizeof__(...) | Returns size in memory, in bytes | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __trunc__(...) | Truncating an Integral returns itself. | | __xor__(self, value, /) | Return self^value. | | bit_length(...) | int.bit_length() -> int | | Number of bits necessary to represent self in binary. | >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 | | conjugate(...) | Returns self, the complex conjugate of any int. | | from_bytes(...) from builtins.type | int.from_bytes(bytes, byteorder, *, signed=False) -> int | | Return the integer represented by the given array of bytes. | | The bytes argument must either support the buffer protocol or be an | iterable object producing bytes. Bytes and bytearray are examples of | built-in objects that support the buffer protocol. | | The byteorder argument determines the byte order used to represent the | integer. If byteorder is 'big', the most significant byte is at the | beginning of the byte array. If byteorder is 'little', the most | significant byte is at the end of the byte array. To request the native | byte order of the host system, use `sys.byteorder' as the byte order value. | | The signed keyword-only argument indicates whether two's complement is | used to represent the integer. | | to_bytes(...) | int.to_bytes(length, byteorder, *, signed=False) -> bytes | | Return an array of bytes representing an integer. | | The integer is represented using length bytes. An OverflowError is | raised if the integer is not representable with the given number of | bytes. | | The byteorder argument determines the byte order used to represent the | integer. If byteorder is 'big', the most significant byte is at the | beginning of the byte array. If byteorder is 'little', the most | significant byte is at the end of the byte array. To request the native | byte order of the host system, use `sys.byteorder' as the byte order value. | | The signed keyword-only argument determines whether two's complement is | used to represent the integer. If signed is False and a negative integer | is given, an OverflowError is raised. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | denominator | the denominator of a rational number in lowest terms | | imag | the imaginary part of a complex number | | numerator | the numerator of a rational number in lowest terms | | real | the real part of a complex number
>
>=
<
<=
==
!=
in
True
True
False
False
3 > 2
True
5 <= 1
False
1 != 2
True
5 in [1, 2, 3, 4, 5]
True
bool(0) # 用 bool 來看各個資料是 True 還是 False
False
bool(42)
True
bool(""), bool("abc")
(False, True)
bool(tuple()), bool((1, 2))
(False, True)
bool([]), bool([1, 2])
(False, True)
bool(set()), bool({1, 2})
(False, True)
bool(dict()), bool({'a': 1, 'b': 42})
(False, True)
if 3 > 2:
print('Yes')
else:
print('Nooooooo, why can you come here?') # 如果 3 > 2 的話印出 'Yes',否則印出 'Nooooooo, why can you come here?'
# 注意縮排是有影響的
Yes
if 2 > 3:
print('No')
elif 5 > 4:
print('Yes')
else:
print('@_@?') # 如果 2 > 3 的話印出 'No',要不然 5 > 4 的話就印出 'Yes',否則印出 '@_@?'
Yes
for i in [1, 2, 3, 4]: # i 會依序變成 1, 2, 3, 4 來執行下面 block 的程式,在這邊則是會被印出來
print(i)
1 2 3 4
for i in [1, 2, 3, 4]:
if i == 3:
break # 使用 break 來提早離開,當 i 變成 3 時就離開這個 for loop
print(i)
1 2
for i in [1, 2, 3, 4]:
print(i)
else:
print('End') # 如果前面的 for 成功跑完的話會執行這段
1 2 3 4 End
for i in [1, 2, 3, 4]:
if i == 3:
break
print(i)
else:
print('End') # 如果前面的 for 成功跑完的話會執行這段
1 2
for i in [1, 2, 3, 4]:
if i == 3:
continue # continue 可以跳過這次後面的 code,進入下一輪
print(i)
else:
print('End') # 如果前面的 for 成功跑完的話會執行這段
1 2 4 End
i = 4
while i > 0: # 當 while 後面接的條件一直符合時就會繼續執行
print(i)
i = i - 1
4 3 2 1
i = 4
while i > 0: # 當 while 後面接的條件一直符合時就會繼續執行
print(i)
i = i - 1
else:
print('End')
4 3 2 1 End
i = 4
while i > 0: # 當 while 後面接的條件一直符合時就會繼續執行
if i == 3:
break
print(i)
i = i - 1
else:
print('End')
4
start:stop[:step]
'{} | {}'.format(1, 2) # 用 {} 表示要留著填空,後面用 .format 傳入要填進去的值
'1 | 2'
'~ {} ~'.format([1, 2, 3, 4])
'~ [1, 2, 3, 4] ~'
'上上下下' + '左右左右' + 'BA' # 用 + 可以把字串接起來
'上上下下左右左右BA'
s = 'abcdefghijklmnopqrstuvwxyz'
s[0]
'a'
s[1:4] # index 1 到 index 3 (index 4 結束)
'bcd'
s[-1] # 負的 index 會倒回去
'z'
s[1:8:2] # index 1 到 index 7,每次跳兩步
'bdfh'
s[-1:-9:-2]
'zxvt'
s[::-1] # 不指定的話會自動帶入值
'zyxwvutsrqponmlkjihgfedcba'
一些常用的 code 會寫成 function,之後要使用時直接呼叫就可以了
def hello(): # 用 def 定義一個 function 叫作 hello,負責輸出 'Hello ~'
print('Hello ~')
hello() # 呼叫
Hello ~
def f_42():
return 42 # 用 return 來回傳資料
x = f_42()
print(x)
42
def f(a, b=3): # a 和 b 是參數,b 預設是 3
return a+b
x = f(10)
y = f(10, 5)
print(x, y)
13 15
"
'
"""
'''
\
escape|
&
^
>
>=
<
<=
==
!=
in
start:stop[:step]
*
**
[名詞解釋]
Python 官方實作,核心部份使用 C 語言撰寫,部份 Standard Library 使用 Python 撰寫,對於 Python 的支援最完整。
利用 JIT (just-in-time compiler) 技術加速 Python 程式的專案,目標是要相容於 CPython 的同時大幅提升效能。
[更多訊息]
PyPy 是用 RPython framework 撰寫的 Python interpreter,RPython 是一個 Python 的子集,RPython 限制了一些比較動態的 feature, 藉此可以做 type inference,之後再做分析、優化,並生出 Tracing JIT、Garbage Collector。
Java 版的 Python 實作,可以把 Python code 轉成 Java bytecode 在 JVM (Java Virtual Machine) 執行,除此之外可以 import Java 的 class
利用 .NET framework 實作的 Python,可以使用 .NET framework 的 libraries