<span style="font-size:18px;">>>> lang = "python" >>> if lang == "C": ... print "C language" ... elif lang == "Java": ... print "Java language" ... else: ... print "Python language" ... Python language >>> </span><span style="font-size:14px;"> </span>
<span style="font-size:18px;">>>> count = 0 >>> while(count < 9): ... print 'the index is:', count ... count += 1 ... the index is: 0 the index is: 1 the index is: 2 the index is: 3 the index is: 4 the index is: 5 the index is: 6 the index is: 7 the index is: 8 >>> </span><span style="font-size:14px;"> </span>
<span style="font-size:18px;">>>> game = ['LOL', 'GT', 'CSOL'] >>> for g in game: ... print 'you play %s' % game ... you play ['LOL', 'GT', 'CSOL'] you play ['LOL', 'GT', 'CSOL'] you play ['LOL', 'GT', 'CSOL'] >>> for index in range(len(game)): ... print 'you play %s' % game[index] ... you play LOL you play GT you play CSOL >>> </span><span style="font-size:14px;"> </span>
<span style="font-size:18px;">def showMaxFactor(num):
count = num/2
while count > 1:
if num % count == 0:
print 'largest factor of %d is %d' % (num, count)
break;
count -= 1
else:
print num, 'is prime'
for eachNum in range(10,21):
showMaxFactor(eachNum)</span><span style="font-size:14px;">
</span>运行结果:<span style="font-size:18px;">linux-ne7w:~/python> python maxFact.py largest factor of 10 is 5 11 is prime largest factor of 12 is 6 13 is prime largest factor of 14 is 7 largest factor of 15 is 5 largest factor of 16 is 8 17 is prime largest factor of 18 is 9 19 is prime largest factor of 20 is 10</span><span style="font-size:14px;"> </span>
<span style="font-size:18px;">>>> t = (123, 'text', 66.66) >>> t (123, 'text', 66.66) >>> i = iter(t) >>> i.next() 123 >>> i.next() 'text' >>> i.next() 66.66 >>> i.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> </span><span style="font-size:14px;"> </span>若在实际应用中,这样写实在够呛。
<span style="font-size:18px;">>>> f = open('text.txt', 'r')
>>> for eachLine in f:
... print eachLine,
...
This is just for a test
everyone should learn programming, programming teach you thinking.
forget my poor english.haha.</span><span style="font-size:14px;">
</span>for循环会自动调用迭代器的next()方法,并处理StopIteration异常。<span style="font-size:18px;">[x ** 2 for x in range(6)] [0, 1, 4, 9, 16, 25] >>> seq = [11, 10, 89, 32, 43, 22, 55, 23, 21, 32] >>> [x for x in seq if x % 2] [11, 89, 43, 55, 23, 21]</span>
<span style="font-size:18px;">>>> [(x+1,y+1) for x in range(3) for y in range(4)] [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4)] >>> </span><span style="font-size:14px;"> </span>
原文地址:http://blog.csdn.net/u012088213/article/details/45014241