1、if 语句
>>> num =input('Please input a number:')
Please input anumber:2
>>> if num>0:
print'%s is positive' % num
2、else 子句
>>> num =int(raw_input("Please input the number:"))
Please input thenumber:0
>>> if num> 0:
... print "%s is positive." % num
... else:
... print "%s is zero or negatie." %num
...
0 is zero ornegatie.
3、elif 子句
>>> num =int(raw_input("Please input the number:"))
Please input thenumber:-2
>>> if num> 0:
... print "%s is positive." % num
... elif num == 0:
... print "%s is zero." % num
... else:
... print "%s is negative." % num
...
-2 is negative.
4、while 循环
>>> name =''
>>> whilenot name:
... name = raw_input("Please input yourname:")
...
Please input yourname:
Please input yourname:
Please input yourname:tom
5、for 循环
>>> sum = 0
>>> for iin range(1,101):
... sum = sum + i
...
>>> printsum
5050
#计算1到100的和
6、循环遍历字典元素
>>> d ={'x':1, 'y':2, 'z':3}
>>> for keyin d:
... print key, 'corresponds to ', d[key]
...
y correspondsto 2
x correspondsto 1
z correspondsto 3
>>> forkey, value in d.items():
... print key, 'corresponds to ', value
...
y correspondsto 2
x correspondsto 1
z correspondsto 3
7、并行迭代
>>> names =['anne', 'beth', 'george', 'damon']
>>> ages =[15,23,40,100]
>>> for iin range(len(names)):
... print names[i], 'is', ages[i], 'yearsold.'
...
anne is 15 yearsold.
beth is 23 yearsold.
george is 40 yearsold.
damon is 100 yearsold.
>>> forname, age in zip(names, ages):
... print name, 'is', age, 'years old.'
...
anne is 15 yearsold.
beth is 23 yearsold.
george is 40 yearsold.
damon is 100 yearsold.
zip函数可以用来进行并行迭代,可以把两个序列压缩在一起,然后返回一个元组的列表。
zip函数可以用于任意多的序列,当最短的序列用完就会停止。
>>>zip(range(5), xrange(1000))
[(0, 0), (1, 1), (2,2), (3, 3), (4, 4)]
>>> strings= ['bob', 'tom', 'python', 'delpi', 'java','tom']
>>>
>>>
>>> forstring in strings:
... if string == "tom":
... strings[strings.index(string)] ="Jaccccccccccck"
...
>>> strings
['bob','Jaccccccccccck', 'python', 'delpi', 'java', 'Jaccccccccccck']
>>> strings= ['bob', 'tom', 'python', 'delpi', 'java','tom']
>>>
>>>
>>> forindex, string in enumerate(strings):
... if 'tom' in string:
... strings[index] = 'Jacccccccccccck'
...
>>> strings
['bob','Jacccccccccccck', 'python', 'delpi', 'java', 'Jacccccccccccck']
enumerate函数在提供索引的地方迭代索引-值对
8、列表推导式
>>> [x forx in range(20)]
[0, 1, 2, 3, 4, 5,6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [x forx in range(20) if x%2 ==0 ]
[0, 2, 4, 6, 8, 10,12, 14, 16, 18]
>>> [ (x,y)for x in range(5) for y in range(3)]
[(0, 0), (0, 1), (0,2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4,0), (4, 1), (4, 2)]