1. 程式人生 > >Python筆記之入門(基礎篇)

Python筆記之入門(基礎篇)

Python 3筆記之入門

Python簡單介紹

  Python 是一個高層次的結合瞭解釋性、編譯性、互動性和麵向物件的指令碼語言。Python 的設計具有很強的可讀性,相比其他語言經常使用英文關鍵字,其他語言的一些標點符號,它具有比其他語言更有特色語法結構。
  

  • Python 是一種解釋型語言: 這意味著開發過程中沒有了編譯這個環節。類似於PHP和Perl語言。
  • Python 是互動式語言: 這意味著,您可以在一個Python提示符,直接互動執行寫你的程式。
  • Python 是面嚮物件語言: 這意味著Python支援面向物件的風格或程式碼封裝在物件的程式設計技術。
  • Python 是初學者的語言:Python 對初級程式設計師而言,是一種偉大的語言,它支援廣泛的應用程式開發,從簡單的文書處理到 WWW 瀏覽器再到遊戲。

Python 環境搭建

  1. 作業系統: win8 64bit
  2. 下載響應的win平臺的Python安裝包 下載連結,將下載的安裝包按照提示安裝。
  3. 環境變數配置
    程式和可執行檔案可以在許多目錄,而這些路徑很可能不在作業系統提供可執行檔案的搜尋路徑中。

Python 中文編碼

關於在sublime text中中文編碼的支援的問題
使用Sublime在build python程式時,有時候會遇到Decode error -output not utf-8或者是cp936。
原因是python編譯執行後的流的編碼方式和Sublime的解碼方式不同,Sublime Ctrl+B build一個python程式時,
輸出output not cp936,說明Sublime中的Python build預設接收的編碼是cp936,
如果你的python 程式是utf-8編碼,有漢字輸出時,Sublime就會報not cp936的錯誤。
如果報的是output not utf-8,說明python在編譯執行原始碼後預設將輸出結果以cp936編碼傳送給Sublime。
而Sublime中的預設接收編碼是utf-8。Sublime Text在接收到python輸出後,試圖以utf-8編碼cp936編碼的流。
當cp936編碼的流中沒有中文字元時,用utf-8解碼不會出錯,當cp936編碼的流中有中文字元時,因為漢子集在cp936與utf-8的編碼不相容,所以用utf-8解碼就會報錯。
解決問題的關鍵就是弄明白你的python程式的編碼和Sublime的python build中指定的編碼。
python sublime decode errorcp936 utf-8 output not utf-8utf-8 cp936 output not cp936比如,你的python程式碼中制定了編碼格式是utf-8,現在sublime報錯了output not cp936的錯誤,則設定Sublime中python build編碼格式為utf-8,反之亦然。Python.sublime-build
位置:


Sublime Text 2 : SublimeText2/Data/Packages/Python/ Python.sublime-build
Sublime Text 3 :SublimeText3/Packages/Python.sublime-package
Python.sublime-build檔案:

{
"cmd": ["python", "-u", "$file"],
"file_regex": "^[ ]*File /"(...*?)/", line ([0-9]*)",
"selector": "source.python",
"encoding":"utf-8"
}

input函式問題解決

關於使用者輸入的互動問題在sublime text中解決。
Sublime3編譯Python程式EOFError:EOF when reading a line。
具體的解決辦法已經在網上找到,連結在這裡,希望對你能夠有幫助。總的來講就是:

  1. 下載一個SublimeRepl外掛;
  2. 將外掛放在如下圖所示的位置location
  3. 執行的時候按照下圖選擇:
    這裡寫圖片描述
    解決方案
#!/usr/bin/python
print ("dddd中國")
if True:
    print ("true");
    print ('true你好')
else:
    print ("false");
    print ("dddd中國")

word = 'word'
sentence = "這是一個句子。"
paragraph = """這是一個段落。
包含了多個語句"""
print (paragraph)

'''
註釋
多行註釋
'''
item_one=1;
item_two=2;
item_three=4
total = item_one + \
        item_two + \
        item_three;

print (total);

import sys; 
x = 'runoob'; 
sys.stdout.write(x + '\n')

import sys
print (sys.stdin.encoding);
print (sys.stdout.encoding);


x = 'runoob'; 
sys.stdout.write(x + '\n')
#input("\n\nPress the enter key to exit.")
#測試輸入效果
xx=input("\n\nPress the enter key to exit:");
print (“當前的字元”+xx);

基礎語法的參考教程

這裡寫連結內容
其中這個教程主要是面向python2的,因此一些python3中有區別的地方,我在下面給出一下程式碼案例:

資料型別

import sys
print (sys.stdin.encoding);
print (sys.stdout.encoding);


#自動型別包裝
counter = 100 # 賦值整型變數
miles = 1000.0 # 浮點型
name = "John" # 字串

print (counter)
print (miles)
print (name)

a, b, c = 1, 2, "john"
print (a)
print (b)
print (c)

##Number  數字資料型別用於儲存數值。
var1 = 1
print (var1)
var2 = 10

##String 字串或串(String)是由數字、字母、下劃線組成的一串字元。
str = 'Hello World!'
print (str) # 輸出完整字串
print (str[0]) # 輸出字串中的第一個字元
print (str[2:5]) # 輸出字串中第三個至第五個之間的字串
print (str[2:]) # 輸出從第三個字元開始的字串
print (str * 2) # 輸出字串兩次
print (str + "TEST") # 輸出連線的字串
##list 
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list # 輸出完整列表
print list[0] # 輸出列表的第一個元素
print list[1:3] # 輸出第二個至第三個的元素 
print list[2:] # 輸出從第三個開始至列表末尾的所有元素
print tinylist * 2 # 輸出列表兩次
##元組
tou1 = ('11','33','23','1234124');
print (tou1);
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );

print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])

tup3=tup1+tup2;

print (tup3);

#任意無符號的物件,用逗號隔開 預設為元組
print ('abc', -4.24e93, 18+6.6j, 'xyz');
x, y = 1, 2;
print ("Value of x , y : ", x,y);


dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

del dict['Name']; # 刪除鍵是'Name'的條目
#dict.clear();     # 清空詞典所有條目
#del dict ;        # 刪除詞典

print ("dict['Age']: ", dict['Age']);
#print ("dict['School']: ", dict['School']);

運算子

  • 算術運算子
  • 比較(關係)運算子
  • 賦值運算子
  • 邏輯運算子
  • 位運算子
  • 成員運算子
  • 身份運算子
  • 運算子優先順序
##算術運算子
a = 21
b = 10
c = 0

c = a + b
print ("1 - c 的值為:", c)

c = a - b
print ("2 - c 的值為:", c)

c = a * b
print ("3 - c 的值為:", c) 

c = a / b
print ("4 - c 的值為:", c)

c = a % b
print ("5 - c 的值為:", c)

# 修改變數 a 、b 、c
a = 2
b = 3
c = a**b 
print ("6 - c 的值為:", c)

a = 10
b = 5
c = a//b 
print ("7 - c 的值為:", c)

##比較運算子
a = 21
b = 10
c = 0

if ( a == b ):
   print ("1 - a 等於 b")
else:
   print ("1 - a 不等於 b")

if ( a != b ):
   print ("2 - a 不等於 b")
else:
   print ("2 - a 等於 b")

if ( a < b ):
   print ("4 - a 小於 b") 
else:
   print ("4 - a 大於等於 b")

if ( a > b ):
   print ("5 - a 大於 b")
else:
   print ("5 - a 小於等於 b")

# 修改變數 a 和 b 的值
a = 5;
b = 20;
if ( a <= b ):
   print ("6 - a 小於等於 b")
else:
   print ("6 - a 大於  b")

if ( b >= a ):
   print ("7 - b 大於等於 b")
else:
   print ("7 - b 小於 b")
##Python賦值運算子
#
a=6;
c=2;
c **= a
print ("6 - c 的值為:", c)

c //= a
print ("7 - c 的值為:", c)

##Python位運算子
c = a ^ b;        # 49 = 0011 0001
print ("3 - c 的值為:", c)

c = ~a;           # -61 = 1100 0011
print ("4 - c 的值為:", c)

c = a << 2;       # 240 = 1111 0000
print ("5 - c 的值為:", c)

c = a >> 2;       # 15 = 0000 1111
print ("6 - c 的值為:", c)

##Python邏輯運算子
#
a = 10
b = 20

if ( a and b ):
   print ("1 - 變數 a 和 b 都為 true")
else:
   print ("1 - 變數 a 和 b 有一個不為 true")

if ( a or b ):
   print ("2 - 變數 a 和 b 都為 true,或其中一個變數為 true")
else:
   print ("2 - 變數 a 和 b 都不為 true")

# 修改變數 a 的值
a = 0
if ( a and b ):
   print ("3 - 變數 a 和 b 都為 true")
else:
   print ("3 - 變數 a 和 b 有一個不為 true")

if ( a or b ):
   print ("4 - 變數 a 和 b 都為 true,或其中一個變數為 true")
else:
   print ("4 - 變數 a 和 b 都不為 true")

if not( a and b ):
   print ("5 - 變數 a 和 b 都為 false,或其中一個變數為 false")
else:
   print ("5 - 變數 a 和 b 都為 true")

##Python成員運算子
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];

if ( a in list ):
   print ("1 - 變數 a 在給定的列表中 list 中")
else:
   print ("1 - 變數 a 不在給定的列表中 list 中")

if ( b not in list ):
   print ("2 - 變數 b 不在給定的列表中 list 中")
else:
   print ("2 - 變數 b 在給定的列表中 list 中")

# 修改變數 a 的值
a = 2
if ( a in list ):
   print ("3 - 變數 a 在給定的列表中 list 中")
else:
   print ("3 - 變數 a 不在給定的列表中 list 中")

##Python身份運算子
a = 20
b = 20

if ( a is b ):
   print ("1 - a 和 b 有相同的標識")
else:
   print ("1 - a 和 b 沒有相同的標識")

if ( id(a) == id(b) ):
   print ("2 - a 和 b 有相同的標識")
else:
   print ("2 - a 和 b 沒有相同的標識")

# 修改變數 b 的值
b = 30
if ( a is b ):
   print ("3 - a 和 b 有相同的標識")
else:
   print ("3 - a 和 b 沒有相同的標識")

if ( id(a) is not id(b) ):
   print ("4 - a 和 b 沒有相同的標識")
else:
   print ("4 - a 和 b 有相同的標識")

##Python運算子優先順序
a = 20
b = 10
c = 15
d = 5
e = 0

e = (a + b) * c / d       #( 30 * 15 ) / 5
print ("(a + b) * c / d 運算結果為:",  e)


運算子優先順序

基本語句

##While
i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # 非雙數時跳過輸出
        continue
    print (i)         # 輸出雙數2、4、6、8、10

i = 1
while 1:            # 迴圈條件為1必定成立
    print (i)         # 輸出1~10
    i += 1
    if i > 10:     # 當i大於10時跳出迴圈
        break

##for 迴圈語句
for letter in 'Python':     # 第一個例項
   print ('當前字母 :', letter)

fruits = ['banana', 'apple',  'mango']
for f in fruits:
    print ("當前字母",f);

for index in range(len(fruits)):
   print ('當前fruit :', fruits[index])
##python 中,for … else 表示這樣的意思,
#for 中的語句和普通的沒有區別,else 中
#的語句會在迴圈正常執行完(即 for 不是通過 break 跳出而中斷的)的情況下執行,while … else 也是一樣。
for num in range(10,20):  # 迭代 10 到 20 之間的數字
   for i in range(2,num): # 根據因子迭代
      if num%i == 0:      # 確定第一個因子
         j=num/i          # 計算第二個因子
         print ('%d 等於 %d * %d' % (num,i,j))
         break            # 跳出當前迴圈
   else:                  # 迴圈的 else 部分
      print (num, '是一個質數')
###else是在for正常執行結束之後才會執行else

'''
Python break語句,就像在C語言中,打破了最小封閉for或while迴圈。
break語句用來終止迴圈語句,即迴圈條件沒有False條件或者序列還沒被完全遞迴完,也會停止執行迴圈語句。
break語句用在while和for迴圈中。
如果您使用巢狀迴圈,break語句將停止執行最深層的迴圈,並開始執行下一行程式碼。
'''

'''
Python continue 語句跳出本次迴圈,而break跳出整個迴圈。
continue 語句用來告訴Python跳過當前迴圈的剩餘語句,然後繼續進行下一輪迴圈。
continue語句用在while和for迴圈中。
'''

for letter in 'Python':     # 第一個例項
   if letter == 'h':
      continue
   print ('當前字母 :', letter)

var = 10                    # 第二個例項
while var > 0:              
   var = var -1
   if var == 5:
      break;
   print ('當前變數值 :', var)

'''
Python pass 語句
Python pass是空語句,是為了保持程式結構的完整性。
pass 不做任何事情,一般用做佔位語句。
'''
for letter in 'Python':
   if letter == 'h':
      pass
      print ('這是 pass 塊')
   print ('當前字母 :', letter)
##字串格式化輸出
print ("My name is %s and weight is %d kg!" % ('Zara', 21) )

hi = '''hi 
there'''
repr(hi)
print (repr(hi));
print (str(hi))
hi #repr


list = ['physics', 'chemistry', 1997, 2000];

print ("Value available at index 2 : ")
print (list[2]);
list[2] = 2001;
print ("New value available at index 2 : ")
print (list[2]);

print (len(list));

print (1997 in list);
print (list *4);
print (list[1:]);
print (list[1:3]);
print (list[-2]);
list.append(122);
print (list)
print (list.count(122));
#print (list.reverse());
print (list);
print (len(list));

mylist = ['aa','cc','bb'];
print (mylist);
print (min(mylist));

print (max(mylist));

print (list.reverse());

日期時間函式


##常用的工具函式
import time;  # 引入time模組

ticks = time.time()


print ("當前時間戳為:", ticks)

print (time.localtime(time.time()));

# 格式化成2016-03-20 11:45:39形式
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) 

# 格式化成Sat Mar 28 22:24:24 2016形式
print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) )

# 將格式字串轉換為時間戳
t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)
secs = time.mktime( t )
print ("time.mktime(t) : %f" % secs)
print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs)))


##calendar
# 獲得今天的日期,並計算昨天和明天的日期
'''
You have a file called operator.py in the current directory,
so import operator is picking up your module and not the Python standard library module operator.

You should rename your file to not conflict with Python's standard library.
'''
import datetime
import calendar

today = datetime.date.today()
yesterday = today - datetime.timedelta(days = 1)
tomorrow = today + datetime.timedelta(days = 1)

print(yesterday, today, tomorrow)


last_friday = datetime.date.today()
oneday = datetime.timedelta(days = 1)

while last_friday.weekday() != calendar.FRIDAY:
    last_friday -= oneday

print(last_friday.strftime('%A, %d-%b-%Y'))


today = datetime.date.today()
target_day = calendar.FRIDAY; #目標
print ("目標",target_day)

this_day = today.weekday(); #今天的星期
print ("today",this_day)

delta_to_target = (this_day - target_day) % 7

print ("求餘",delta_to_target)

va = (0-4)%7;##負數求模就是做差
print (va)

last_friday = today - datetime.timedelta(days = delta_to_target)

print(last_friday.strftime("%d-%b-%Y"))

def total_timer(times):
    td = datetime.timedelta(0)
    duration = sum([datetime.timedelta(minutes = m, seconds = s) for m, s in times], td)
    return duration

times1 = [(2, 36),
          (3, 35),
          (3, 45),
          ]
times2 = [(3, 0),
          (5, 13),
          (4, 12),
          (1, 10),
          ]

assert total_timer(times1) == datetime.timedelta(0, 596)
assert total_timer(times2) == datetime.timedelta(0, 815)

print("Tests passed.\n"
      "First test total: %s\n"
      "Second test total: %s" % (total_timer(times1), total_timer(times2)))
##函式
def printme(str):
    "列印任何傳入的字串"
    print (str)
    return

printme("我要呼叫使用者自定義函式!");
printme("再次呼叫同一函式");

##notice list in python is 廣義表
def changeme(mylist):
    "change the list getted"
    mylist.append([1,2,3,4])
    print ("in the function Value",mylist)
    return

mylist=[5,6,7]
changeme(mylist)
print (mylist)

printme(str = "My string");

#可寫函式說明
def printinfo( name, age ):
   "列印任何傳入的字串"
   print ("Name: ", name);
   print ("Age ", age);
   return;

#呼叫printinfo函式
printinfo( age=50, name="miki" );

# 可寫函式說明
def printinfo1( arg1, *vartuple ):
   "列印任何傳入的引數"
   print ("輸出: ")
   print (arg1)
   for var in vartuple:
      print (var)
   return;

# 呼叫printinfo 函式
printinfo1( 10 );
printinfo1( 70, 60, 50 );

# 可寫函式說明
sum = lambda arg1, arg2: arg1 + arg2;

# 呼叫sum函式
print ("相加後的值為 : ", sum( 10, 20 ))
print ("相加後的值為 : ", sum( 20, 20 ))

min = lambda a1,a2,a3: a1+a2+a3;
print (min(1,3,4))

檔案IO

# 開啟一個檔案
fo = open("data.py", "wb")
print ("檔名: ", fo.name)
print ("是否已關閉 : ", fo.closed)
print ("訪問模式 : ", fo.mode)
#print ("末尾是否強制加空格 : ", fo.softspace)
#fo.close()

fo = open("foo.txt", "w")
fo.write( "www.runoob.com!\nVery good site!\n");

fo = open("foo.txt", "r+")
str = fo.read(10);
print ("讀取的字串是 : ", str)
# 關閉開啟的檔案
fo.close()

fo = open("foo.txt", "r+")
str = fo.read(10);
print ("讀取的字串是 : ", str)

# 查詢當前位置
position = fo.tell();
print ("當前檔案位置 : ", position)
str = fo.read(10);
print (str);

# 把指標再次重新定位到檔案開頭
position = fo.seek(0, 0);
str = fo.read(10);
print ("重新讀取字串 : ", str)
# 關閉開啟的檔案
fo.close()


import os;
'''
os.mkdir("newdir");
os.chdir("newdir");
print (os.getcwd());
'''
fo = open("foo.txt", "r")
print ("檔名為: ", fo.name)

line = fo.readline()
print ("讀取第一行 %s" % (line))

line = fo.readline(5)
print ("讀取的字串為: %s" % (line))

# 關閉檔案
fo.close()

# 開啟檔案
fo = open("foo.txt", "r+")
print ("檔名為: ", fo.name)

# 擷取10個位元組
fo.truncate(5)##擷取部分字元

str = fo.read()
print ("讀取資料222: %s" % (str))

# 關閉檔案
fo.close()

# 開啟檔案
fo = open("test.txt", "w")
print ("檔名為: ", fo.name)
str = "菜鳥教程"
fo.write( str )

fo = open("test.txt", "r")
print (fo.readlines());

# 關閉檔案
fo.close()


異常的使用


try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print ("Error: can\'t find file or read data")
else:
   print ("Written content in the file successfully")
   fh.close()

try:
    fo=open("test","r");
except IOError:
    print ("exception raise!");
else:
    print ("read ok");
    fo.close();
##自定義異常
class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg

try:
   raise Networkerror("Bad hostname")
except Networkerror as e:
   print (e.args)