栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 3.7极速入门教程5循环

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 3.7极速入门教程5循环

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 pure
robin 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
...
apple
banana
orange
pear

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

>>> 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()


条件循环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()



作者:python作业AI毕业设计
链接:https://www.jianshu.com/p/648d26e30d1d


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/221785.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号