zoukankan      html  css  js  c++  java
  • python基础之循环与迭代器

    循环

     python 循环语句有for循环和while循环。

    while循环
    while循环语法
    while 判断条件:
        语句
    #while循环示例
    i = 0
    while i < 10:
        i += 1;
        print(i)
    while else 语句 语法
    while 判断条件:
        语句
    else:
        语句
    #while else 示例
    n = 0
    while n < 10:
        n += 1;
        print(n);
    else:
        print("n不小于10")

    for循环

    for循环可以变量任何序列项目,比如list,set,tuple,字符串。
    for循环语法:
    for 变量 in 序列:
        语句
    else:
        语句
    #for循环示例
    str = "1234567890";
    for s in  str:
        print(s);
    迭代器
    迭代器是一个可以记住遍历的位置的对象。
    迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
    迭代器有两个基本的方法:iter()创建迭代器 和 next()访问迭代器。
    字符串,集合,列表或元组对象都可用于创建迭代器。
    #使用for循环访问示例
    tuple = (1,2,3,4,5)
    it = iter(tuple)
    for x in it:
        print(x)
    
    #使用while循环访问示例
    import sys
    ite = iter(tuple)
    while True:
        try:
           print (next(ite))
        except StopIteration:
            sys.exit()
     



  • 相关阅读:
    Python subprocess方法
    Python hashlib、hmac加密模块
    mysql binlog详解
    Nginx 关键字详解
    账号笔记
    Python configparser模块
    Python yaml处理
    Linux && 与 ||
    spring boot 学习(十一)使用@Async实现异步调用
    spring boot 学习(十)SpringBoot配置发送Email
  • 原文地址:https://www.cnblogs.com/jottings/p/9936574.html
Copyright © 2011-2022 走看看