Python2.5/2.6實用教程 入門基礎篇

來源:互聯網
上載者:User
起步走

代碼如下:


#! /usr/bin/python

a=2
b=3
c="test"
c=a+b
print "execution result: %i"%c


知識點

Python是動態語言,變數不須預先聲明.
列印語句採用C風格
字串和數字
但有趣的是,在javascript裡我們會理想當然的將字串和數字串連,因為是動態語言嘛.但在Python裡有點詭異,如下:

代碼如下:


#! /usr/bin/python

a=2
b="test"
c=a+b



運行這行程式會出錯,提示你字串和數字不能串連,於是只好用內建函數進行轉換

代碼如下:


#! /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函數將字串和數字進行轉換
列印以#開頭,而不是習慣的//
列印多個參數的方式
國際化
寫膩了英文注釋,我們要用中文!


#! /usr/bin/python
# -*- coding: utf8 -*-

print "上帝重返人間:馬拉多納出任阿根廷國家足球隊主帥."
知識點:

加上字元集即可使用中文
列表
列表類似Javascript的數組,方便易用

代碼如下:



#! /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


知識點:

列表長度是動態,可任意添加刪除元素.
用索引可以很方便訪問元素,甚至返回一個子列表
更多方法請參考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]


知識點:

將他當Java的Map來用即可.
字串
比起C/C++,Python處理字串的方式實在太讓人感動了.把字串當列表來用吧.

代碼如下:


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字串的區別:

代碼如下:


#! /usr/bin/python
# -*- coding: utf8 -*-

s=raw_input("輸入你的中文名,按斷行符號繼續");
print "你的名字是 : " +s;

l=len(s)
print "你中文名字的長度是:"+str(l);
a=unicode(s,"utf8")
l=len(a)
print "對不起,剛才計算錯誤.我們應該用utf8來計算中文字串的長度, \
你名字的長度應該是:"+str(l);


知識點:

用unicode函數進行轉碼
條件和迴圈語句

代碼如下:


#! /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)


知識點:

條件和迴圈語句
如何得到控制台輸入
函數

代碼如下:


#! /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


一個好用的函數

代碼如下:


#! /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 不用{}來控製程序結構,他強迫你用縮排來寫程式,使代碼清晰.
定義函數方便簡單
方便好用的range函數
異常處理

代碼如下:


#! /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!"

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.