條件判斷、循環

1if 語句

>>> num =input('Please input a number:')

Please input anumber:2

>>> if num>0:

print'%s is positive' % num

 

2else 子句

>>> 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.

 

3elif 子句

 

>>> 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.

 

4while 循環

>>> name =''

>>> whilenot name:

...     name = raw_input("Please input yourname:")

...

Please input yourname:

Please input yourname:

Please input yourname:tom

 

5for 循環

>>> sum = 0

>>> for iin range(1,101):

...     sum = sum + i

...

>>> printsum

5050

#計算1100的和

 

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)]

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章