发布时间:2019-08-06 13:55:38编辑:auto阅读(1540)
最近倒腾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
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]
每个元素由一对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
所以用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
但是不同在于 for循环的else 只有在for正常退出时才会执行,当for循环由break退出时不执行
the else
statement
is executed after the for
, but only if
thefor
ends normally—that is, not with abreak
.
上一篇: python编程之函数思想
下一篇: 为初学者准备的15本免费Python电子
47495
45796
36794
34326
28969
25599
24444
19612
19112
17634
5467°
6049°
5571°
5639°
6574°
5377°
5379°
5886°
5856°
7172°