[course]03 —— Python循环
EX32
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
p = 0
# 迭代 iterator
for number in the_count:
print("This is count %d" % number)
print(number)
print(p)
# same as above
for fruit in fruits:
print("A fruit of type: %s" % fruit)
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print("I got %r" % i)
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print("Adding %d to the list." % i)
# append is a function that lists understand
elements.append(i)
print(elements)
# now we can print them out too
for i in elements:
print("Element was: %d" % i)
index = 0
while index < len(elements):
print(elements[index])
index += 1EX33
1. for循环和range
range方法的使用,第一个参数指定开始,第二个参数指定到哪里结束(<)
不使用range的计算方式
如果range只写一个参数则默认从0开始
Copy Visualize Run
range的第三个参数代表步长(step)
计算m到n之间的奇数之和
使用步长来计算
2. 循环嵌套
循环可以嵌套使用,在循环嵌套的时候更要注意两次循环的次数
使用循环来写*
3. while循环
Example: nth positive integer with some property
Misuse: While loop over a fixed range
4. break 和 continue
break: 结束当前循环 continue: 跳出当次循环,继续执行下一次循环
Copy Visualize Run
while true循环的跳出
5. 素数
使用循环来求素数
更快的查询素数的方式
验证
6. 计算第n个素数
Last updated
Was this helpful?