python中迴圈的寫法 for

2021-06-21 23:15:52 字數 2072 閱讀 7764

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

發現了個叫codecademy的**,還不錯

1. list

names = ["adam","alex","mariah","martine","columbus"]

for name in names:

print name

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

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

2. dictionary

webster = 

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

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)

輸出:

3917

1530

7 python中 for和while 都有else

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

theelsestatement is executed after thefor, but 

only

if theforends normally—that is, not with abreak.

python 迴圈高階寫法 python 005

while迴圈 while迴圈 適用於明確知道迴圈結束的條件但是不知道迴圈次數 語法 while 迴圈條件判斷 迴圈語句 while迴圈可以提到for in遍歷,但是for in遍歷不能替代while迴圈 while迴圈可以替代for in遍歷 使用迴圈完成1 100的所有整數之和 sum 0 fo...

for迴圈的更多寫法

在看設計模式這本書,遇到乙個令人疑惑的for迴圈語句 for var i 0,type type string array number i 比較疑惑,因為從平時接觸的來看基本上都是 for 語句1,語句2,語句3 語句1 起始 語句2 迴圈終止條件 語句3 在迴圈後被執行的語句 現在的疑惑如下 f...

python中的for else 寫法

這是python官方文件中combinations的寫法 當迭代的物件迭代完並為空時,位於else的子句將執行,而如果在for迴圈中含有break時則直接終止迴圈,並不會執行else子句。def combinations iterable,r combinations abcd 2 ab ac ad...