例程:
>>> import random
>>> import sys
>>> SecretNumber= random.randint(1,100)
>>> print "i'm thinking of a number between 1 to 100"
i'm thinking of a number between 1 to 100
>>> while(1):
print "Guess my number."
NumberGuess = int(sys.stdin.readline())
if (NumberGuess == SecretNumber):
print "Correct! Choosing a new number..."
SecretNumber = random.randint(1,100)
elif (NumberGuess > SecretNumber):
print "lower."
else:
print "Eigher."
Guess my number.
9
Eigher.
Guess my number.
5
Eigher.
Guess my number.
99
lower.
Guess my number.
56
Eigher.
Guess my number.
77
Eigher.
Guess my number.
88
Eigher.
Guess my number.
95
lower.
Guess my number.
90
Correct! Choosing a new number...
Guess my number.
90
Eigher.
Guess my number.
95
lower.
Guess my number.
95
lower.
Guess my number.
93
lower.
Guess my number.
91
Correct! Choosing a new number...
Guess my number.
92
lower.
Guess my number.
80
Eigher.
Guess my number.
86
lower.
Guess my number.
5
Eigher.
Guess my number.
85
Correct! Choosing a new number...
Guess my number.
一、if语句
if (condition):
expression
else:
expression
二、while语句
while (expression):
if (condition):
expression
elif:
expression
...
else:
expression
三、for循环
for in :
(loop body)
例
>>> import string
>>> def Encode(MessageString):
EncodeList = []
for Char in MessageString:
EncodeList.append("%x" % ord(Char))
return EncodeList
>>> def Decode(SecretMessage):
DecodedList = []
for hexvalue in SecretMessage:
DecodedList.append(chr(int(hexvalue,16)))
return string.join(DecodedList,"")
>>> if (__name__=="__main__"):
SecretMessage = Encode("remember to drink your Ovaltine!")
print SecretMessage
print Decode(SecretMessage)
['72', '65', '6d', '65', '6d', '62', '65', '72', '20', '74', '6f', '20', '64', '72', '69', '6e', '6b', '20', '79', '6f', '75', '72', '20', '4f', '76', '61', '6c', '74', '69', '6e', '65', '21']
remember to drink your Ovaltine!
>>>
中断和继续
continue和break
例打印0~99之间的偶数,循环一次,删除没有处理的序列的第一个数据,打印第二个元素。
>>> MyRange = range(100)
>>> for x in MyRange:
print x
del MyRange[0]
错误处理机制
try块和finally块
try块捕捉错误
finally是放置必须执行的代码块
四、利用断言进行调试