Python2.5/2.6實用教程 入門基礎(chǔ)篇
更新時間:2009年11月29日 21:17:46 作者:
本文方便有經(jīng)驗的程序員進入Python世界.本文適用于python2.5/2.6版本.
起步走
#! /usr/bin/python
a=2
b=3
c="test"
c=a+b
print "execution result: %i"%c
知識點
Python是動態(tài)語言,變量不須預(yù)先聲明.
打印語句采用C風(fēng)格
字符串和數(shù)字
但有趣的是,在javascript里我們會理想當(dāng)然的將字符串和數(shù)字連接,因為是動態(tài)語言嘛.但在Python里有點詭異,如下:
#! /usr/bin/python
a=2
b="test"
c=a+b
運行這行程序會出錯,提示你字符串和數(shù)字不能連接,于是只好用內(nèi)置函數(shù)進行轉(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)
知識點:
用int和str函數(shù)將字符串和數(shù)字進行轉(zhuǎn)換
打印以#開頭,而不是習(xí)慣的//
打印多個參數(shù)的方式
國際化
寫膩了英文注釋,我們要用中文!
#! /usr/bin/python
# -*- coding: utf8 -*-
print "上帝重返人間:馬拉多納出任阿根廷國家足球隊主帥."
知識點:
加上字符集即可使用中文
列表
列表類似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
知識點:
列表長度是動態(tài)的,可任意添加刪除元素.
用索引可以很方便訪問元素,甚至返回一個子列表
更多方法請參考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]
知識點:
將他當(dāng)Java的Map來用即可.
字符串
比起C/C++,Python處理字符串的方式實在太讓人感動了.把字符串當(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("輸入你的中文名,按回車繼續(xù)");
print "你的名字是 : " +s;
l=len(s)
print "你中文名字的長度是:"+str(l);
a=unicode(s,"utf8")
l=len(a)
print "對不起,剛才計算錯誤.我們應(yīng)該用utf8來計算中文字符串的長度, \
你名字的長度應(yīng)該是:"+str(l);
知識點:
用unicode函數(shù)進行轉(zhuǎn)碼
條件和循環(huán)語句
#! /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)
知識點:
條件和循環(huán)語句
如何得到控制臺輸入
函數(shù)
#! /usr/bin/python
# -*- coding: utf8 -*-
def sum(a,b):
return a+b
func = sum
r = func(5,6)
print r
# 提供默認值
def add(a,b=2):
return a+b
r=add(1)
print r
r=add(1,5)
print r
一個好用的函數(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
知識點:
Python 不用{}來控制程序結(jié)構(gòu),他強迫你用縮進來寫程序,使代碼清晰.
定義函數(shù)方便簡單
方便好用的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
知識點
Python是動態(tài)語言,變量不須預(yù)先聲明.
打印語句采用C風(fēng)格
字符串和數(shù)字
但有趣的是,在javascript里我們會理想當(dāng)然的將字符串和數(shù)字連接,因為是動態(tài)語言嘛.但在Python里有點詭異,如下:
復(fù)制代碼 代碼如下:
#! /usr/bin/python
a=2
b="test"
c=a+b
運行這行程序會出錯,提示你字符串和數(shù)字不能連接,于是只好用內(nèi)置函數(shù)進行轉(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)
知識點:
用int和str函數(shù)將字符串和數(shù)字進行轉(zhuǎn)換
打印以#開頭,而不是習(xí)慣的//
打印多個參數(shù)的方式
國際化
寫膩了英文注釋,我們要用中文!
#! /usr/bin/python
# -*- coding: utf8 -*-
print "上帝重返人間:馬拉多納出任阿根廷國家足球隊主帥."
知識點:
加上字符集即可使用中文
列表
列表類似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
知識點:
列表長度是動態(tài)的,可任意添加刪除元素.
用索引可以很方便訪問元素,甚至返回一個子列表
更多方法請參考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]
知識點:
將他當(dāng)Java的Map來用即可.
字符串
比起C/C++,Python處理字符串的方式實在太讓人感動了.把字符串當(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("輸入你的中文名,按回車繼續(xù)");
print "你的名字是 : " +s;
l=len(s)
print "你中文名字的長度是:"+str(l);
a=unicode(s,"utf8")
l=len(a)
print "對不起,剛才計算錯誤.我們應(yīng)該用utf8來計算中文字符串的長度, \
你名字的長度應(yīng)該是:"+str(l);
知識點:
用unicode函數(shù)進行轉(zhuǎn)碼
條件和循環(huán)語句
復(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)
知識點:
條件和循環(huán)語句
如何得到控制臺輸入
函數(shù)
復(fù)制代碼 代碼如下:
#! /usr/bin/python
# -*- coding: utf8 -*-
def sum(a,b):
return a+b
func = sum
r = func(5,6)
print r
# 提供默認值
def add(a,b=2):
return a+b
r=add(1)
print r
r=add(1,5)
print r
一個好用的函數(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
知識點:
Python 不用{}來控制程序結(jié)構(gòu),他強迫你用縮進來寫程序,使代碼清晰.
定義函數(shù)方便簡單
方便好用的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!"
相關(guān)文章
Pytorch中torch.nn.Softmax的dim參數(shù)用法說明
這篇文章主要介紹了Pytorch中torch.nn.Softmax的dim參數(shù)用法說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06Django基于Models定制Admin后臺實現(xiàn)過程解析
這篇文章主要介紹了Django基于Models定制Admin后臺實現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11趣味Python實戰(zhàn)練習(xí)之自動更換桌面壁紙腳本附源碼
讀萬卷書不如行萬里路,學(xué)的扎不扎實要通過實戰(zhàn)才能看出來,本篇文章手把手帶你編寫一個自動更換桌面壁紙的腳本,代碼簡潔而且短,相信你一定看得懂,大家可以在過程中查缺補漏,看看自己掌握程度怎么樣2021-10-10