1. 程式人生 > >python中迴圈的寫法 for

python中迴圈的寫法 for

最近倒騰python,希望能堅持下去吧

發現了個叫codecademy的網站,還不錯http://www.codecademy.com/courses/python-beginner-en-IZ9Ra/0/1?curriculum_id=4f89dab3d788890003000096

1. list

names = ["Adam","Alex","Mariah","Martine","Columbus"]
for name in names:
    print name

在上面這段中,names是一個list, 它的構成是[ ],每個元素之間用,分隔

name表明names中的每一個變數,注意for的那一條語句要加冒號

2. dictionary

webster = {
	"Aardvark" : "A star of a popular children's cartoon show.",
    "Baa" : "The sound a goat makes.",
    "Carpet": "Goes on the floor.",
    "Dab": "A small amount."
}

# Add your code below!
for key in webster:
    print webster[key]

在這段中,webster是一個dictionary,由{ }構成,每個元素之間用,分隔

每個元素由一對key和value構成,中間由:分隔

"Aardvark" : "A star of a popular children's cartoon show."

上一條語句中key是"Aardvark"  value是"A star of a popular children's cartoon show."

for迴圈中的變數是每一個元素的key,所以要列印對應的value時需要webster[key]這種方式來訪問

3.string

for letter in "Codecademy":
    print letter

對於string來說,相當於每一個字母為元素構成的list

所以用for來訪問的時候相當於訪問的是每一個字母

4. range()

n=[1,2,3,4,5]
for i in range(0, len(n)):
    n[i] = n[i] * 2


5.enmerate 是一個build in function 可以同時提供 index和item

choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item
輸出;
Your choices are:
1 pizza
2 pasta
3 salad
4 nachos
None

6. zip  zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.

list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]

for a, b in zip(list_a, list_b):
    # Add your code here!
    print max(a,b)

輸出:
3
9
17
15
30

7 python中 for和while 都有else

但是不同在於 for迴圈的else 只有在for正常退出時才會執行,當for迴圈由break退出時不執行

 the else statement is executed after the for, but only if thefor ends normally—that is, not with abreak.