一、if语句
代码语言:javascript复制>>> x = int(raw_input("Please enter an integer: "))Please enter an integer: 42>>> if x < 0:... x = 0... print 'Negative changed to zero'... elif x == 0:... print 'Zero'... elif x == 1:... print 'Single'... else:... print 'More'
二、for 语句
代码语言:javascript复制In [5]: words = ['cat', 'window', 'defenestrate']
In [6]: for w in words:
...: print w, len(w)
...:
cat 3
window 6
defenestrate 12
三、 range函数
代码语言:javascript复制In [8]: range(5, 10)
Out[8]: [5, 6, 7, 8, 9]
In [9]: range(0, 10, 3)
Out[9]: [0, 3, 6, 9]
In [10]: range(-10, -100, -30)
Out[10]: [-10, -40, -70]
四、循环语句中的break 、continue和else
代码语言:javascript复制In [14]: for n in range(2,10):
for x in range(2,n):
if n%x==0:
print n,'equals',x,'*',n/x
break
else:
print n,'is a prime number'
....:
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
代码语言:javascript复制In [16]: for num in range(2, 10):
....: if num % 2 == 0:
....: print "Found an even number", num
....: continue
....: print "Found a number", num
....:
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
五、pass语句
代码语言:javascript复制In [18]: def initlog(*args):
....: pass