博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[雪峰磁针石博客]python 3.7极速入门教程5循环
阅读量:7107 次
发布时间:2019-06-28

本文共 4464 字,大约阅读时间需要 14 分钟。

5循环

语法基础

for语句

Python的for语句针对序列(列表或字符串等)中的子项进行循环,按它们在序列中的顺序来进行迭代。

>>> # Measure some strings:... words = ['cat', 'window', 'defenestrate']>>> for w in words:...     print(w, len(w))...cat 3window 6defenestrate 12

在迭代过程中修改迭代序列不安全,可能导致部分元素重复两次,建议先拷贝:

>>> for w in words[:]:  # Loop over a slice copy of the entire list....     if len(w) > 6:...         words.insert(0, w)...>>> words['defenestrate', 'cat', 'window', 'defenestrate']

range()函数

内置函数 range()生成等差数值序列:

>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(10) 生成了一个包含10个值的链表,但是不包含最右边的值。默认从0开始,也可以让range 从其他值开始,或者指定不同的增量值(甚至是负数,有时也称"步长"):

>>> range(5, 10)[5, 6, 7, 8, 9]>>> range(0, 10, 3)[0, 3, 6, 9]>>> range(-10, -100, -30)[-10, -40, -70]>>> range(-10, -100, 30)[]

如果迭代时需要索引和值可结合使用range()和len():

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']>>> for i in range(len(a)):...     print(i, a[i])...0 Mary1 had2 a3 little4 lamb

不过使用enumerate()更方便,参见后面的介绍。

break和continue语句及循环中的else子句

break语句和C中的类似,用于终止当前的for或while循环。

循环可能有else 子句;它在循环迭代完整个列表(对于 for)后或执行条件为false(对于 while)时执行,但循环break时不会执行。这点和try...else而不是if...else相近。请看查找素数的程序:

>>> for n in range(2, 10):...     for x in range(2, n):...         if n % x == 0:...             print(n, 'equals', x, '*', n//x)...             break...     else:...         # loop fell through without finding a factor...         print(n, 'is a prime number')...2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3

continue语句也是从C而来,它表示退出当次循环,继续执行下次迭代。通常可以用if...else替代,请看查找偶数的实例:

>>> for n in range(2, 10):...     for x in range(2, n):...         if n % x == 0:...             print(n, 'equals', x, '*', n//x)...             break...     else:...         # loop fell through without finding a factor...         print(n, 'is a prime number')...2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3

pass

pass语句什么也不做。它语法上需要,但是实际什么也不做场合,也常用语以后预留以后扩展。例如:

>>> while True:...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)...>>> class MyEmptyClass:...     pass...>>> def initlog(*args):...     pass   # Remember to implement this!...

循环技巧

在字典中循环时,关键字和对应的值可以使用 items() 方法同时获取:

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}>>> for k, v in knights.items():...     print(k, v)...gallahad the purerobin the brave

在序列中循环时 enumerate() 函数同时得到索引位置和对应值:

>>> for i, v in enumerate(['tic', 'tac', 'toe']):...     print(i, v)...0 tic1 tac2 toe

同时循环两个或更多的序列,可以使用 zip() 打包:

>>> questions = ['name', 'quest', 'favorite color']>>> answers = ['lancelot', 'the holy grail', 'blue']>>> for q, a in zip(questions, answers):...     print('What is your {0}?  It is {1}.'.format(q, a))...What is your name?  It is lancelot.What is your quest?  It is the holy grail.What is your favorite color?  It is blue.

需要逆向循环序列的话,调用 reversed() 函数即可:

>>> for i in reversed(xrange(1, 10, 2)):...     print(i)...97531

使用 sorted() 函数可排序序列,它不改动原序列,而是生成新的已排序的序列:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> for f in sorted(set(basket)):...     print f...applebananaorangepear

若要在循环时修改迭代的序列,建议先复制。

>>> import math>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]>>> filtered_data = []>>> for value in raw_data:...     if not math.isnan(value):...         filtered_data.append(value)...>>> filtered_data[56.2, 51.7, 55.3, 52.5, 47.8]

循环

image.png

代码:

# -*- coding: utf-8 -*-# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319# 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入) # qq群:144081101 591302926  567351477# CreateDate: 2018-6-12 # bowtie.py# Draw a bowtiefrom turtle import *def polygon(n, length):    """Draw n-sided polygon with given side length."""    for _ in range(n):        forward(length)        left(360/n)        def main():    """Draw polygons with 3-9 sides."""    for n in range(3, 10):        polygon(n, 80)    exitonclick()    main()

参考资料

  • 讨论qq群144081101 591302926 567351477 钉钉免费群21745728
  • 谢谢点赞!

条件循环while

image.png

代码:

# -*- coding: utf-8 -*-# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319# 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入) # qq群:144081101 591302926  567351477# CreateDate: 2018-6-12 # spiral.py# Draw spiral shapesfrom turtle import *def spiral(firststep, angle, gap):    """Move turtle on a spiral path."""    step = firststep    while step > 0:        forward(step)        left(angle)        step -= gapdef main():    spiral(100, 71, 2)    exitonclick()main()

转载地址:http://nkjhl.baihongyu.com/

你可能感兴趣的文章
《JAVA开发环境的熟悉》实验报告——20145337
查看>>
用于string对象中字符截取的几种函数总结——语法、参数意义及用途举例
查看>>
Android控件— — —ImageView
查看>>
严格模式认识
查看>>
BZOJ 3198 [Sdoi2013]spring
查看>>
删除排序数组中的重复数字
查看>>
js简单倒计时
查看>>
Python基础:语法基础(3)
查看>>
更改具有Foreign key约束的表
查看>>
webpack缓存
查看>>
Java 运算符,条件结构小总结
查看>>
In-Memory:内存优化数据的持久化和还原
查看>>
字符串转换成整数
查看>>
hdu 5475(线段树)
查看>>
Java代码编写的30条建议
查看>>
标准的基于欧式距离的模板匹配算法优源码化和实现(附源代码)。
查看>>
对phpcms中{L('news')}的讲解
查看>>
博客园有感
查看>>
Hibernate三种状态
查看>>
设计模式C#实现(四)——迭代器模式
查看>>