1、python是大小写敏感的语言
2、在书写函数时需定义
例:
def functionname(parameter1[,]):
3、书写控制块的时候需要代码缩进一个Tab键值,一个缩进层等于四个空格,八个空格等于一个制表符。
4、当遇到非缩进代码行时,函数定义结束。
5、控制语句后面都需跟冒号(:),并且控制语句中的语句需要缩进一层。
例(1):
>>> def MyFunction(MyNember):
... if(MyNember == 855):
... print "right"
... else:
... print "worst"
...
>>> MyFunction(5)
worst
>>> MyFunction(855)
right
>>>
例(2):
>>> FoodTuple=("Spam","Egg","Sausage")
>>> FoodTuple=list(FoodTuple)
>>> FoodList
['Spam', 'Egg', 'Sausage']
>>> FoodList[2]
'Sausage'
>>> FoodList[2]="Spam"
>>> NewFoodTuple=tuple(FoodList)
>>> NewFoodTuple
('Spam', 'Egg', 'Spam')
>>>
例(3):
>>> PhoneDict=
>>> EmptyDict={}
>>> PhoneDict["bob"]
'555-1212'
>>> PhoneDict["cindy"]="867-5309"
>>> print "phone list:",PhoneDict
phone list: {'bob': '555-1212', 'cindy': '867-5309', 'fred': '555-3345'}
>>> PhoneDict["luke"]
Traceback (most recent call last):
File "", line 1, in ?
KeyError: 'luke'
>>> PhoneDict.get("joe","unknown")
'unknown'
>>> PhoneDict.get("bob","unknown")
'555-1212'
>>>
>>> DialAJoe=PhoneDict.get("joe",None)
>>> DialAJoe
>>> print DialAJoe
None
>>> DialAJoe=PhoneDict.get("bob",None)
>>> print DialAJoe
555-1212
>>>
6、list(),tuple()可以转换元组和列表
list为列表,tuple为元组
7、变量,常量等基本元素单位不定义就可以使用。和其他的语言不同。
例(4):
>>> import string
>>> def CountWords(Text):
... WordCount={}
... CurrentWord=""
... Text = Text+"."
... PlecesOfWords = string.letters + "'-"
... for CharacterIndex in range(0,len(Text)):
... CurrentCharacter = Text[CharacterIndex]
... if (PlecesOfWords.find(CurrentCharacter)!= -1):
... CurrentWord = CurrentWord + CurrentCharacter
... else:
... if(CurrentWord!=""):
... CurrentWord = string.lower(CurrentWord)
... CurrentCount = WordCount.get(CurrentWord,0)
... WordCount[CurrentWord]=CurrentCount+1
... CurrentWord = ""
... return(WordCount)
... if(__name__=="__main__"):
... TextFile = open("poem.txt","r")
... Text = TextFile.read()
... TextFile.close()
... WordCount = CountWords(Text)
... SortedWords = WordCount.keys()
... SortedWords.sort()
... for Word in SortedWords:
... print Word,WordCount[Word]
...
例(5):
>>> import math
>>> class Point:
def __init__(self,X,Y):
self.X = X
self.Y = Y
def DistanceToPoint(self,OtherPoint):
"Returns the distance from this point to another"
SumOfSquares = ((self.X-OtherPoint.X)**2)+
((self.Y-OtherPoint.Y)**2)
return math.sqrt(SumOfSquares)
def IsInsideCircle(self,Center,Radius):
"""Return 1 if this point is inside the circle,
0 otherwise"""
if (self.DistanceToPoint(Center)<
return 1
else:
return 0
>>> PointA= Point(3,5)
>>> PointB= Point(-4,-4)
>>> print "A to B:",PointA.DistanceToPoint(PointB)
A to B: 11.401754251
>>> print "B to A:",PointB.DistanceToPoint(PointA)
B to A: 11.401754251
>>> CircleCenter = Point(3,3)
>>> print "A in circle:",PointA.IsInsideCircle(CircleCenter,5)
A in circle: 1
>>> print "B in circle:",PointB.IsInsideCircle(CircleCenter,5)
B in circle: 0
>>>
文章来源于领测软件测试网 https://www.ltesting.net/