Python2.5/2.6實(shí)用教程 入門基礎(chǔ)篇
更新時(shí)間:2009年11月29日 21:17:46 作者:
本文方便有經(jīng)驗(yàn)的程序員進(jìn)入Python世界.本文適用于python2.5/2.6版本.
起步走
#! /usr/bin/python
a=2
b=3
c="test"
c=a+b
print "execution result: %i"%c
知識(shí)點(diǎn)
Python是動(dòng)態(tài)語(yǔ)言,變量不須預(yù)先聲明.
打印語(yǔ)句采用C風(fēng)格
字符串和數(shù)字
但有趣的是,在javascript里我們會(huì)理想當(dāng)然的將字符串和數(shù)字連接,因?yàn)槭莿?dòng)態(tài)語(yǔ)言嘛.但在Python里有點(diǎn)詭異,如下:
#! /usr/bin/python
a=2
b="test"
c=a+b
運(yùn)行這行程序會(huì)出錯(cuò),提示你字符串和數(shù)字不能連接,于是只好用內(nèi)置函數(shù)進(jìn)行轉(zhuǎn)換
#! /usr/bin/python
a=2
b="test"
c=str(a)+b
d="1111"
e=a+int(d)
#How to print multiply values
print "c is %s,e is %i" % (c,e)
知識(shí)點(diǎn):
用int和str函數(shù)將字符串和數(shù)字進(jìn)行轉(zhuǎn)換
打印以#開頭,而不是習(xí)慣的//
打印多個(gè)參數(shù)的方式
國(guó)際化
寫膩了英文注釋,我們要用中文!
#! /usr/bin/python
# -*- coding: utf8 -*-
print "上帝重返人間:馬拉多納出任阿根廷國(guó)家足球隊(duì)主帥."
知識(shí)點(diǎn):
加上字符集即可使用中文
列表
列表類似Javascript的數(shù)組,方便易用
#! /usr/bin/python
# -*- coding: utf8 -*-
#定義元組
word=['a','b','c','d','e','f','g']
#如何通過索引訪問元組里的元素
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "
print b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "
print c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "
print d # All elements of word.
#元組可以合并
e=word[:2]+word[2:]
print "e is: "
print e # All elements of word.
f=word[-1]
print "f is: "
print f # The last elements of word.
g=word[-4:-2]
print "g is: "
print g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "
print h # The last two elements.
i=word[:-2]
print "i is: "
print i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
print "Adds new element"
word.append('h')
print word
#刪除元素
del word[0]
print word
del word[1:3]
print word
知識(shí)點(diǎn):
列表長(zhǎng)度是動(dòng)態(tài)的,可任意添加刪除元素.
用索引可以很方便訪問元素,甚至返回一個(gè)子列表
更多方法請(qǐng)參考Python的文檔
字典
#! /usr/bin/python
x={'a':'aaa','b':'bbb','c':12}
print x['a']
print x['b']
print x['c']
for key in x:
print "Key is %s and value is %s",(key,x[key])
keys=x.items();
print keys[0]
keys[0]='ddd'
print keys[0]
知識(shí)點(diǎn):
將他當(dāng)Java的Map來用即可.
字符串
比起C/C++,Python處理字符串的方式實(shí)在太讓人感動(dòng)了.把字符串當(dāng)列表來用吧.
word="abcdefg"
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "+b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "+c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "+d # All elements of word.
e=word[:2]+word[2:]
print "e is: "+e # All elements of word.
f=word[-1]
print "f is: "+f # The last elements of word.
g=word[-4:-2]
print "g is: "+g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "+h # The last two elements.
i=word[:-2]
print "i is: "+i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
不過要注意Asc和Unicode字符串的區(qū)別:
#! /usr/bin/python
# -*- coding: utf8 -*-
s=raw_input("輸入你的中文名,按回車?yán)^續(xù)");
print "你的名字是 : " +s;
l=len(s)
print "你中文名字的長(zhǎng)度是:"+str(l);
a=unicode(s,"utf8")
l=len(a)
print "對(duì)不起,剛才計(jì)算錯(cuò)誤.我們應(yīng)該用utf8來計(jì)算中文字符串的長(zhǎng)度, \
你名字的長(zhǎng)度應(yīng)該是:"+str(l);
知識(shí)點(diǎn):
用unicode函數(shù)進(jìn)行轉(zhuǎn)碼
條件和循環(huán)語(yǔ)句
#! /usr/bin/python
x=int(raw_input("Please enter an integer:"))
if x<0:
x=0
print "Negative changed to zero"
elif x==0:
print "Zero"
else:
print "More"
# Loops List
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
知識(shí)點(diǎn):
條件和循環(huán)語(yǔ)句
如何得到控制臺(tái)輸入
函數(shù)
#! /usr/bin/python
# -*- coding: utf8 -*-
def sum(a,b):
return a+b
func = sum
r = func(5,6)
print r
# 提供默認(rèn)值
def add(a,b=2):
return a+b
r=add(1)
print r
r=add(1,5)
print r
一個(gè)好用的函數(shù)
#! /usr/bin/python
# -*- coding: utf8 -*-
# The range() function
a =range(5,10)
print a
a = range(-2,-7)
print a
a = range(-7,-2)
print a
a = range(-2,-11,-3) # The 3rd parameter stands for step
print a
知識(shí)點(diǎn):
Python 不用{}來控制程序結(jié)構(gòu),他強(qiáng)迫你用縮進(jìn)來寫程序,使代碼清晰.
定義函數(shù)方便簡(jiǎn)單
方便好用的range函數(shù)
異常處理
#! /usr/bin/python
s=raw_input("Input your age:")
if s =="":
raise Exception("Input must no be empty.")
try:
i=int(s)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unknown exception!"
else: # It is useful for code that must be executed if the try clause does not raise an exception
print "You are %d" % i," years old"
finally: # Clean up action
print "Goodbye!"
復(fù)制代碼 代碼如下:
#! /usr/bin/python
a=2
b=3
c="test"
c=a+b
print "execution result: %i"%c
知識(shí)點(diǎn)
Python是動(dòng)態(tài)語(yǔ)言,變量不須預(yù)先聲明.
打印語(yǔ)句采用C風(fēng)格
字符串和數(shù)字
但有趣的是,在javascript里我們會(huì)理想當(dāng)然的將字符串和數(shù)字連接,因?yàn)槭莿?dòng)態(tài)語(yǔ)言嘛.但在Python里有點(diǎn)詭異,如下:
復(fù)制代碼 代碼如下:
#! /usr/bin/python
a=2
b="test"
c=a+b
運(yùn)行這行程序會(huì)出錯(cuò),提示你字符串和數(shù)字不能連接,于是只好用內(nèi)置函數(shù)進(jìn)行轉(zhuǎn)換
復(fù)制代碼 代碼如下:
#! /usr/bin/python
a=2
b="test"
c=str(a)+b
d="1111"
e=a+int(d)
#How to print multiply values
print "c is %s,e is %i" % (c,e)
知識(shí)點(diǎn):
用int和str函數(shù)將字符串和數(shù)字進(jìn)行轉(zhuǎn)換
打印以#開頭,而不是習(xí)慣的//
打印多個(gè)參數(shù)的方式
國(guó)際化
寫膩了英文注釋,我們要用中文!
#! /usr/bin/python
# -*- coding: utf8 -*-
print "上帝重返人間:馬拉多納出任阿根廷國(guó)家足球隊(duì)主帥."
知識(shí)點(diǎn):
加上字符集即可使用中文
列表
列表類似Javascript的數(shù)組,方便易用
復(fù)制代碼 代碼如下:
#! /usr/bin/python
# -*- coding: utf8 -*-
#定義元組
word=['a','b','c','d','e','f','g']
#如何通過索引訪問元組里的元素
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "
print b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "
print c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "
print d # All elements of word.
#元組可以合并
e=word[:2]+word[2:]
print "e is: "
print e # All elements of word.
f=word[-1]
print "f is: "
print f # The last elements of word.
g=word[-4:-2]
print "g is: "
print g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "
print h # The last two elements.
i=word[:-2]
print "i is: "
print i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
print "Adds new element"
word.append('h')
print word
#刪除元素
del word[0]
print word
del word[1:3]
print word
知識(shí)點(diǎn):
列表長(zhǎng)度是動(dòng)態(tài)的,可任意添加刪除元素.
用索引可以很方便訪問元素,甚至返回一個(gè)子列表
更多方法請(qǐng)參考Python的文檔
字典
復(fù)制代碼 代碼如下:
#! /usr/bin/python
x={'a':'aaa','b':'bbb','c':12}
print x['a']
print x['b']
print x['c']
for key in x:
print "Key is %s and value is %s",(key,x[key])
keys=x.items();
print keys[0]
keys[0]='ddd'
print keys[0]
知識(shí)點(diǎn):
將他當(dāng)Java的Map來用即可.
字符串
比起C/C++,Python處理字符串的方式實(shí)在太讓人感動(dòng)了.把字符串當(dāng)列表來用吧.
復(fù)制代碼 代碼如下:
word="abcdefg"
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "+b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "+c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "+d # All elements of word.
e=word[:2]+word[2:]
print "e is: "+e # All elements of word.
f=word[-1]
print "f is: "+f # The last elements of word.
g=word[-4:-2]
print "g is: "+g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "+h # The last two elements.
i=word[:-2]
print "i is: "+i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
不過要注意Asc和Unicode字符串的區(qū)別:
復(fù)制代碼 代碼如下:
#! /usr/bin/python
# -*- coding: utf8 -*-
s=raw_input("輸入你的中文名,按回車?yán)^續(xù)");
print "你的名字是 : " +s;
l=len(s)
print "你中文名字的長(zhǎng)度是:"+str(l);
a=unicode(s,"utf8")
l=len(a)
print "對(duì)不起,剛才計(jì)算錯(cuò)誤.我們應(yīng)該用utf8來計(jì)算中文字符串的長(zhǎng)度, \
你名字的長(zhǎng)度應(yīng)該是:"+str(l);
知識(shí)點(diǎn):
用unicode函數(shù)進(jìn)行轉(zhuǎn)碼
條件和循環(huán)語(yǔ)句
復(fù)制代碼 代碼如下:
#! /usr/bin/python
x=int(raw_input("Please enter an integer:"))
if x<0:
x=0
print "Negative changed to zero"
elif x==0:
print "Zero"
else:
print "More"
# Loops List
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
知識(shí)點(diǎn):
條件和循環(huán)語(yǔ)句
如何得到控制臺(tái)輸入
函數(shù)
復(fù)制代碼 代碼如下:
#! /usr/bin/python
# -*- coding: utf8 -*-
def sum(a,b):
return a+b
func = sum
r = func(5,6)
print r
# 提供默認(rèn)值
def add(a,b=2):
return a+b
r=add(1)
print r
r=add(1,5)
print r
一個(gè)好用的函數(shù)
復(fù)制代碼 代碼如下:
#! /usr/bin/python
# -*- coding: utf8 -*-
# The range() function
a =range(5,10)
print a
a = range(-2,-7)
print a
a = range(-7,-2)
print a
a = range(-2,-11,-3) # The 3rd parameter stands for step
print a
知識(shí)點(diǎn):
Python 不用{}來控制程序結(jié)構(gòu),他強(qiáng)迫你用縮進(jìn)來寫程序,使代碼清晰.
定義函數(shù)方便簡(jiǎn)單
方便好用的range函數(shù)
異常處理
復(fù)制代碼 代碼如下:
#! /usr/bin/python
s=raw_input("Input your age:")
if s =="":
raise Exception("Input must no be empty.")
try:
i=int(s)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unknown exception!"
else: # It is useful for code that must be executed if the try clause does not raise an exception
print "You are %d" % i," years old"
finally: # Clean up action
print "Goodbye!"
您可能感興趣的文章:
- 零基礎(chǔ)寫python爬蟲之爬蟲編寫全記錄
- Python類的基礎(chǔ)入門知識(shí)
- Python正則表達(dá)式之基礎(chǔ)篇
- Python3基礎(chǔ)之list列表實(shí)例解析
- Python學(xué)習(xí)筆記(一)(基礎(chǔ)入門之環(huán)境搭建)
- python基礎(chǔ)教程之基本數(shù)據(jù)類型和變量聲明介紹
- python基礎(chǔ)教程之lambda表達(dá)式使用方法
- Python3基礎(chǔ)之函數(shù)用法
- python3爬蟲之入門基礎(chǔ)和正則表達(dá)式
- Python中一些不為人知的基礎(chǔ)技巧總結(jié)
相關(guān)文章
Pytorch中torch.nn.Softmax的dim參數(shù)用法說明
這篇文章主要介紹了Pytorch中torch.nn.Softmax的dim參數(shù)用法說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06Django基于Models定制Admin后臺(tái)實(shí)現(xiàn)過程解析
這篇文章主要介紹了Django基于Models定制Admin后臺(tái)實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11趣味Python實(shí)戰(zhàn)練習(xí)之自動(dòng)更換桌面壁紙腳本附源碼
讀萬(wàn)卷書不如行萬(wàn)里路,學(xué)的扎不扎實(shí)要通過實(shí)戰(zhàn)才能看出來,本篇文章手把手帶你編寫一個(gè)自動(dòng)更換桌面壁紙的腳本,代碼簡(jiǎn)潔而且短,相信你一定看得懂,大家可以在過程中查缺補(bǔ)漏,看看自己掌握程度怎么樣2021-10-10詳解用Python練習(xí)畫個(gè)美隊(duì)盾牌
這篇文章主要介紹了用Python練習(xí)畫個(gè)美隊(duì)盾牌,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03Python的Django框架中模板碎片緩存簡(jiǎn)介
這篇文章主要介紹了Python的Django框架中模板碎片緩存,包括給cache標(biāo)簽傳遞參數(shù)等方法,需要的朋友可以參考下2015-07-07自動(dòng)化Nginx服務(wù)器的反向代理的配置方法
這篇文章主要介紹了自動(dòng)化Nginx服務(wù)器的反向代理的配置方法,反向代理是Nginx服務(wù)器的招牌功能,需要的朋友可以參考下2015-06-06python opencv攝像頭的簡(jiǎn)單應(yīng)用
這篇文章主要為大家詳細(xì)介紹了python opencv攝像頭的簡(jiǎn)單應(yīng)用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06Python遞歸實(shí)現(xiàn)猴子吃桃問題及解析
這篇文章主要介紹了Python遞歸實(shí)現(xiàn)猴子吃桃問題及解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07