-------------------------------------- 開始之前
IDLE Python GUI 是一個功能完備的程式 IDE ( Integrated Development Environment 整合式開環境 )
Python Shell Python 的互動模式
Tab 建,自動補全關鍵字
Alt + P 回復到上一次編輯的 Python 程式
Alt + N 相反
--------------------------------------3.1 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.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
提姆·彼得斯(Tim Peters)撰寫的《 Python之禪》
美麗勝於醜陋。
顯式勝於隱式。
簡單勝於復雜。
複雜勝於復雜。
扁平比嵌套更好。
稀疏勝於密集。
可讀性很重要。
特殊情況還不足以打破規則。
儘管實用性勝過純度。
錯誤絕不能默默傳遞。
除非明確地保持沉默。
面對模棱兩可的想法,拒絕猜測的誘惑。
應該有一種-最好只有一種-顯而易見的方法。
儘管除非您是荷蘭人,否則一開始這種方式可能並不明顯。
現在總比沒有好。
儘管從來沒有比現在“正確”好。
如果實現難以解釋,那是個壞主意。
如果實現易於解釋,則可能是個好主意。
命名空間是一個很棒的主意-讓我們做更多這些吧!
--------------------------------------3.2 輸入與輸出
3.2.1 print
>>> print("Hello Python!")
Hello Python!
name="kk"
print("Hello %s ,Nice to meet you!" %name) # %s 字串
Hello kk ,Nice to meet you!
age=27
print("You are %d !" %age) # %d 數字
You are 27 !
n=100
print("You print is %r !" %n) # %r 不知列印類型
n="ABC"
print("You print is %r !" %n)
You print is 100 !
You print is 'ABC' !
3.2.2 input
n=input("Enter any content:")
print ("Your input is %r" %n)
Enter any content:Tom
Your input is 'Tom'
3.2.3 引號與註釋
Python 不區分單引號與雙引號
# 單行註釋
"""或 ''' 三個引號表示多行註釋,不區分單引號與雙引號
--------------------------------------3.3 分支與循環
3.3.1 if 敘述
a=2
b=3
if a>b:
print("a max!")
else:
print("b is max!")
b is max!
name="Tom"
if name=="Tom": # 相等 == , 不相等 !=
print("Tom,you are on duty today.")
else:
print("Please call Tom to duty")
Tom,you are on duty today.
string="Hello World"
if "Hello" in string: # not in 表示不包含
print("Contain")
else:
print("Not Contain")
Contain
a=True
if a:
print("a is True")
else:
print("a is not True")
a is True
results=72
if results >= 90:
print('優秀')
elif results >= 70:
print('良好')
elif results >= 60:
print('及格')
else:
print('不及格')
良好
3.3.2 for 敘述
print(i)
H
e
l
l
o
W
o
r
l
d
fruits=["banana","apple","mango"] #字典
for i in fruits:
print(i)
banana
apple
mango
for i in range(4+1): #進行一定次數的循環
print(i)
0
1
2
3
4
#range(start,end[,step])預設從0開始循環,也可設定起始位置和步進值,Python3 range()是一個陣列
for i in range(1,9+1,2):
print(i)
1
3
5
7
9
--------------------------------------3.4陣列 [ ]與字典 { }
3.4.1 陣列
>>> lists=[1,2,3,'a',5]
>>> lists
[1, 2, 3, 'a', 5]
>>> lists[0]
1
>>> lists[4]
5
>>> lists[4]='b'
>>> lists[4]
'b'
>>> lists.append('c')
>>> lists
[1, 2, 3, 'a', 'b', 'c']
3.4.2 字典
>>> dicts={'na':'Tom','pwd':123456}
>>> dicts.keys()
dict_keys(['na', 'pwd'])
>>> dicts.values()
dict_values(['Tom', 123456])
>>> dicts.items()
dict_items([('na', 'Tom'), ('pwd', 123456)])
>>> for i in dicts.items():
print(i)
('na', 'Tom')
('pwd', 123456)
>>> for k,v in dicts.items():
print("dicts key is %r" %k)
print("dicts values is %r" %v)
dicts key is 'na'
dicts values is 'Tom'
dicts key is 'pwd'
dicts values is 123456
>>> key=['b','a','c','e','d']
>>> value=['2','1','3','5','4']
>>> for k,v in zip(key,value): #zip 方法合併2個 List 為 Dictionary
print(k,v)
b 2
a 1
c 3
e 5
d 4
-------------------------------------- 3.5 函數、類別和方法
3.5.1 函數
def add(a,b):
print(a+b)
add(3,5)
8
def add(a,b):
return (a+b)
print(add(3,5))
8
def add(a=1,b=2):
return a+b
print(add()) #沒傳參數就使用預設參數
print(add(3,5))
3
8
3.5.2 類別和方法
#class A(object): 所有類別預設繼承 object,所以不宣告也可以
class A():
#方法第一個參數必須存在,一般習慣命名 self,呼叫方法時不需為這參數傳值
def add(self,a,b):
return a+b
cnt=A()
print(cnt.add(3,5))
class A():
#建立類別時首先宣告初始化的方法 _ _init_ _
def __init__(self,a,b):
self.a=int(a)
self.b=int(b)
def add(self):
return self.a+self.b
cnt=A('4',5)
print(cnt.add())
9
class A():
def add(self,a,b):
return a+b
class B(A): #B類別繼承A類別
def sub(self,a,b):
return a-b
print(B().add(3,5))
8
-------------------------------------- 3.6 模組
3.6.1 參考模組
>>> import time
>>> help(time)
Help on built-in module time:
.
.
.
>>> print(time.ctime())
Fri Jan 24 08:51:44 2020
>>> from time import ctime
>>> print(ctime())
Fri Jan 24 08:53:48 2020
from time import *
print(ctime())
print("休眠2秒")
sleep(2)
print(ctime())
Fri Jan 24 08:57:56 2020
休眠2秒
Fri Jan 24 08:57:58 2020
3.6.2 模組呼叫
# project/pub.py
def add(a,b):
return a+b
# project/count.py
from pub import add
print(add(4,5))
9
# 在 project/ 下多了一個檔案 __pycache__/pub.cpython-38.pyc 預先編譯的模組,為了加強模組載入速度
3.6.3 跨目錄模組呼叫
# project/model/pub.py
def add(a,b):
return a+b
# project/count.py
from model.pub import add
print(add(4,5))
9
3.6.4 進一步討論跨目錄模組呼叫
# \project\model\count.py
class A():
def add(self,a,b):
return a+b
# \project\model\new_count.py
from .count import A
class B(A):
def sub(self,a,b):
return a-b
resule=B().add(2,5)
print(resule)
# \project\test.py
import sys
sys.path.append("./model")
from model import new_count
test=new_count.B()
test.add(2,5)
7
3.7.1 認識例外
Python 用例外物件 exception object 來表示例外情況 ,遇到錯誤後會引發例外。如果例外物件並未處理或捕捉,則程式就會用回溯 Traceback 來終止執行。
>>> open("abc.txt",'r')
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
open("abc.txt",'r')
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'
# 透過 open() 方法,以讀 'r' 的方式開啟不存在的檔案
try:
open("abc.txt",'r')
except FileNotFoundError:
print("例外了!")
例外了!
>>> print(aa)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print(aa)
NameError: name 'aa' is not defined
try:
open(aa)
except NameError:
print("例外了!")
例外了!
在 Python 中所有的例外類別都繼承 BaseException,所以可使用它來接收所有類型例外
try:
open(aa)
except BaseException:
print("例外了!")
例外了!
# 告訴我們例外的原因
try:
print(aa)
except BaseException as msg:
print(msg)
name 'aa' is not defined
3.7.2 更多例外用法
try:
print(aa)
except BaseException as msg:
print(msg)
else:
print("沒有例外!")
name 'aa' is not defined
try:
aa="例外測試"
print(aa)
except BaseException as msg:
print(msg)
else:
print("沒有例外!")
例外測試
沒有例外!
try:
aa="例外測試"
print(aa)
except BaseException as msg:
print(msg)
else:
print("沒有例外!")
finally:
print("不管是否例外,都會被執行。")
例外測試
沒有例外!
不管是否例外,都會被執行。
3.7.3 拋出例外
from random import randint
N=randint(1,9)
if N%2==0:
raise BaseException("%d is even" %N)
else:
raise BaseException("%d is odd" %N)
Traceback (most recent call last):
File "C:/Users/kk/Desktop/0.py", line 4, in <module>
raise BaseException("%d is even" %N)
BaseException: 8 is even
N=randint(1,9)
if N%2==0:
raise BaseException("%d is even" %N)
else:
raise BaseException("%d is odd" %N)
Traceback (most recent call last):
File "C:/Users/kk/Desktop/0.py", line 4, in <module>
raise BaseException("%d is even" %N)
BaseException: 8 is even
沒有留言:
張貼留言