本文適合有Java編程經驗的程序員快速熟悉Python,本文程序在windows xp+python3.1a1測試經過。
本文提到的idle指python shell,即安裝python後你在菜單看到的IDLE(python gui),在idle裏ctrl+n能夠打開一個新窗口,輸入源碼後ctrl+s能夠保存,f5運行程序。凡打開新窗口即指ctrl+n的操做。 javascript
1
2
3
4
5
6
|
#打開新窗口,輸入:
#! /usr/bin/python<BR># -*- coding: utf8 -*-
s1=input("Input your name:")
print("你好,%s"
%
s1)
'''
|
知識點:
* input("某字符串")函數:顯示"某字符串",並等待用戶輸入.
* print()函數:如何打印.
* 如何應用中文
* 如何用多行註釋
'''
但有趣的是,在javascript裏咱們會理想固然的將字符串和數字鏈接,由於是動態語言嘛.但在Python裏有點詭異,以下: java
1
2
3
|
#! /usr/bin/python
a=2<BR>b="test"
c=a+b
|
運行這行程序會出錯,提示你字符串和數字不能鏈接,因而只好用內置函數進行轉換 python
1
2
3
4
5
6
7
8
9
10
|
#! /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函數將字符串和數字進行轉換
* 打印以#開頭,而不是習慣的//
* 打印多個參數的方式
'''
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
#! /usr/bin/python
# -*- coding: utf8 -*-
#列表相似Javascript的數組,方便易用
#定義元組
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的文檔
'''
1
2
3
4
5
6
7
8
|
#! /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]))
'''
|
知識點:
* 將他當Java的Map來用便可.
'''
比起C/C++,Python處理字符串的方式實在太讓人感動了.把字符串當列表來用吧. 程序員
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#! /usr/bin/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))
|
中文和英文的字符串長度是否同樣? shell
1
2
3
4
5
6
|
#! /usr/bin/python
# -*- coding: utf8 -*-
s=input("輸入你的中文名,按回車繼續");
print
("你的名字是 : "
+s)
l=len(s)
print
("你中文名字的長度是:"+str(l))
|
知識點:
相似Java,在python3裏全部字符串都是unicode,因此長度一致.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#! /usr/bin/python
#條件和循環語句
x=int(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))
|
#知識點:
# * 條件和循環語句
# * 如何獲得控制檯輸入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
#! /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
(1,10)
for
i
in
a:
print
(i)
a
=
range(-2,-11,-3)
# The 3rd parameter stands for step
for
i
in
a:
print
(i)
|
知識點:
Python 不用{}來控制程序結構,他強迫你用縮進來寫程序,使代碼清晰.
定義函數方便簡單
方便好用的range函數
1
2
3
4
5
6
7
8
9
10
|
#! /usr/bin/python
s=input("Input your age:")
if
s
=="":
raise
Exception("Input must no be empty.")
try:
i=int(s)
except
Exception as err:
print(err)
finally:
# Clean up action
print("Goodbye!")
|
對比Java,python的文本處理再次讓人感動 編程
1
2
3
4
5
6
7
8
9
10
|
#! /usr/bin/python
spath="D:/download/baa.txt"
f=open(spath,"w")
# Opens file for writing.Creates this file doesn't exist.
f.write("First line 1.\n")
f.writelines("First line 2.")
f.close()
f=open(spath,"r")
# Opens file for reading
for
line
in
f:
print("每一行的數據是:%s"%line)
f.close()
|
知識點:
open的參數:r表示讀,w寫數據,在寫以前先清空文件內容,a打開並附加內容.
打開文件以後記得關閉
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class
Base:
def
__init__(self):
self.data
=
[]
def
add(self, x):
self.data.append(x)
def
addtwice(self, x):
self.add(x)
self.add(x)
# Child extends Base
class
Child(Base):
def
plus(self,a,b):
return
a+b
oChild
=Child()
oChild.add("str1")
print
(oChild.data)
print
(oChild.plus(2,3))
'''
|
知識點:
* self:相似Java的this參數
'''
每個.py文件稱爲一個module,module之間能夠互相導入.請參看如下例子: windows
1
2
3
4
5
6
7
8
|
# a.py
def
add_func(a,b):
return
a+b
# b.py
from
a
import
add_func
# Also can be : import a
print
("Import add_func from module a")
print
("Result of 1 plus 2 is: ")
print
(add_func(1,2))
# If using "import a" , then here should be "a.add_func"
|
module能夠定義在包裏面.Python定義包的方式稍微有點古怪,假設咱們有一個parent文件夾,該文件夾有一個child子文件夾.child中有一個module a.py . 如何讓Python知道這個文件層次結構?很簡單,每一個目錄都放一個名爲_init_.py 的文件.該文件內容能夠爲空.這個層次結構以下所示: 數組
1
2
3
4
5
|
parent
--__init_.py<BR>--child
--
__init_.py
--a.py
b.py
|
那麼Python如何找到咱們定義的module?在標準包sys中,path屬性記錄了Python的包路徑.你能夠將之打印出來: app
1
2
|
import
sys
print(sys.path)
|
一般咱們能夠將module的包路徑放到環境變量PYTHONPATH中,該環境變量會自動添加到sys.path屬性.另外一種方便的方法是編程中直接指定咱們的module路徑到sys.path 中: 函數
1
2
3
4
5
6
7
8
9
10
|
import
sys
import
os
sys.path.append(os.getcwd()+'\\parent\\child')
print(sys.path)
from
a
import
add_func
print
(sys.path)
print
("Import add_func from module a")
print
("Result of 1 plus 2 is: ")
print
(add_func(1,2))
|
知識點:
如何定義模塊和包
如何將模塊路徑添加到系統路徑,以便python找到它們
如何獲得當前路徑
對比C++,Java的突出進步是內建Javadoc機制,程序員能夠經過閱讀Javadoc瞭解函數用法.Python也內建了一些方便函數以便程序員參考.
dir函數: 查看某個類/對象的方法. 若是有某個方法想不起來,請敲dir. 在idle裏,試試 dir(list)
help函數: 詳細的類/對象介紹. 在idle裏, 試試 help(list)
本文轉至python腳本之家,整理過程當中因對python僅知皮毛,文中代碼不免有不當之處,尤爲是縮進方面,還請你們多多包含