GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • 首页
  • HTML
  • JavaScript
  • CSS
  • React
  • Python3
  • Java
  • C
  • C++
  • C#
  • Go
  • SQL
  • Linux
  • VS Code

This view

  • Original page
  • New address

GeezerVison is showing www.runoob.com — Python for 循环语句 | 菜鸟教程

菜鸟教程 -- 学的不仅是技术,更是梦想!

  • Vue3 教程
  • Vue2 教程
  • Bootstrap3
  • Bootstrap4
  • Bootstrap5
  • 机器学习
  • PyTorch
  • TensorFlow
  • Sklearn
  • NLP
  • AI Agent
  • Ollama
  • Coding Plan
Python 基础教程
Python 基础教程 Python 简介 Python 环境搭建 Python 中文编码 Python VS Code Python 基础语法 Python 变量类型 Python 运算符 Python 条件语句 Python 循环语句 Python While 循环语句 Python for 循环语句 Python 循环嵌套 Python break 语句 Python continue 语句 Python pass 语句 Python Number(数字) Python 字符串 Python 列表(List) Python 元组 Python 字典(Dictionary) Python 日期和时间 Python 函数 Python 模块 Python 文件I/O Python File 方法 Python 异常处理 Python OS 文件/目录方法 Python 内置函数

Python 高级教程

Python 面向对象 Python 正则表达式 Python CGI 编程 Python MySQL Python 网络编程 Python SMTP Python 多线程 Python XML 解析 Python GUI 编程(Tkinter) Python2.x 与 3​​.x 版本区别 Python IDE Python JSON Python AI 绘画 Python 100例 Python 测验
Python While 循环语句
Python 循环嵌套

Python for 循环语句

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

语法:

for循环的语法格式如下:

for iterating_var in sequence:
   statements(s)

流程图:

实例:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- for letter in 'Python': # 第一个实例 print("当前字母: %s" % letter) fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # 第二个实例 print ('当前水果: %s'% fruit) print ("Good bye!")

尝试一下 »

以上实例输出结果:

当前字母: P
当前字母: y
当前字母: t
当前字母: h
当前字母: o
当前字母: n
当前水果: banana
当前水果: apple
当前水果: mango
Good bye!


通过序列索引迭代

另外一种执行循环的遍历方式是通过索引,如下实例:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print ('当前水果 : %s' % fruits[index]) print ("Good bye!")

以上实例输出结果:

当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!

以上实例我们使用了内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。



循环使用 else 语句

在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- for num in range(10,20): # 迭代 10 到 20 (不包含) 之间的数字 for i in range(2,num): # 根据因子迭代 if num%i == 0: # 确定第一个因子 j=num/i # 计算第二个因子 print ('%d 等于 %d * %d' % (num,i,j)) break # 跳出当前循环 else: # 循环的 else 部分 print ('%d 是一个质数' % num)

尝试一下 »

以上实例输出结果:

10 等于 2 * 5
11 是一个质数
12 等于 2 * 6
13 是一个质数
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一个质数
18 等于 2 * 9
19 是一个质数

更多实例:python 打印菱形、三角形、矩形

AI 思考中...
Python While 循环语句
Python 循环嵌套

10 篇笔记 写笔记

  1. #0

       缘分天注定

      738***[email protected]

      参考地址

    134

    使用内置 enumerate 函数进行遍历:

    for index, item in enumerate(sequence):
        process(index, item)
    

    实例

    >>> sequence = [12, 34, 34, 23, 45, 76, 89]
    >>> for i, j in enumerate(sequence):
    ...     print i,j
    ... 
    0 12
    1 34
    2 34
    3 23
    4 45
    5 76
    6 89
    
    缘分天注定

       缘分天注定

      738***[email protected]

      参考地址

    10年前 (2017-02-27)
  2. #0

       shenwenwin

      she***[email protected]

    60

    for 使用案例

    使用list.append()模块对质数进行输出。

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    # 输出 2 到 100 简的质数
    prime = []
    for num in range(2,100):  # 迭代 2 到 100 之间的数字
       for i in range(2,num): # 根据因子迭代
          if num%i == 0:      # 确定第一个因子
             break            # 跳出当前循环
       else:                  # 循环的 else 部分
          prime.append(num)
    print prime
    

    输出结果:

    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    shenwenwin

       shenwenwin

      she***[email protected]

    10年前 (2017-04-19)
  3. #0

       kimiYang

      943***[email protected]

    39

    打印空心等边三角形:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    # 打印空心等边三角形 
    rows = int(raw_input('输入行数:'))
    for i in range(0, rows):
        for k in range(0, 2 * rows - 1):
            if (i != rows - 1) and (k == rows - i - 1 or k == rows + i - 1):
                print " * ",
            elif i == rows - 1:
                if k % 2 == 0:
                    print " * ",
                else:
                    print "   ",
            else:
                print "   ",
        print "\n"
    
    kimiYang

       kimiYang

      943***[email protected]

    10年前 (2017-05-05)
  4. #0

       feng

      124***[email protected]

    24

    打印1-9三角形阵列:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    for i in range(1,11):
        for k in range(1,i):
            print k,
        print "\n"
    

    输出结果:

    1 
    
    1 2 
    
    1 2 3 
    
    1 2 3 4 
    
    1 2 3 4 5 
    
    1 2 3 4 5 6 
    
    1 2 3 4 5 6 7 
    
    1 2 3 4 5 6 7 8 
    
    1 2 3 4 5 6 7 8 9 
    
    feng

       feng

      124***[email protected]

    10年前 (2017-06-08)
  5. #0

       ljm

      131***[email protected]

    23
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    '''在python中,for循环后的in跟随一个序列的话,循环每次使用的序列元素,而不是序列
    的下标'''
    s = 'qazxswedcvfr'
    for i in range(0,len(s),2):
        print s[i]
    '''enumerate() :
        在每次循环中,可以同时得到下标和元素
        际上,enumerate(),在每次循环中返回的是包含每个元素的定值表,两个元素分别赋值
     index,char'''
    for (index,char) in enumerate(s):
        print "index=%s ,char=%s" % (index,char)
    ljm

       ljm

      131***[email protected]

    10年前 (2017-06-27)
  6. #0

       为梦而来

      183***[email protected]

    25

    冒泡排序,来至于高学军:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    # 冒泡排序# 定义列表 list
    arays = [1,8,2,6,3,9,4]
    for i in range(len(arays)):
        for j in range(i+1):
            if arays[i] < arays[j]:
                # 实现连个变量的互换
                arays[i],arays[j] = arays[j],arays[i]
    print arays
    为梦而来

       为梦而来

      183***[email protected]

    9年前 (2017-08-02)
  7. #0

       forMyPeople

      lwy***[email protected]

    24

    更多实例:python 打印菱形、三角形、矩形的代码感觉,写的有点复杂了,如果让你画圆或者其他图形呢?

    其实运用数学公式,就可以了。比如菱形 |x - w/2| + |y - w/2| = w/2 轻松搞定。

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    width = int(raw_input('输入对角线长度: '))
    for row in range(width + 1):
        for col in range(width + 1):
            if ((abs(row - width/2) + abs(col - width/2)) == width/2):
                print "*",
            else:
                print " ",
        print " "
    forMyPeople

       forMyPeople

      lwy***[email protected]

    9年前 (2017-09-12)
  8. #0

       冷火

      jes***[email protected]

    28

    Python for 常用实例说明:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    print "for循环只能执行range内两数字相减次数"
    for i in range(1,10):     # 只能执行9次,判断循环终止条件是 >= 第二个数字 10 就不再执行 和 其他语言的 i=1 to 10 不同
        print 'i=:', i
    
    print "使用xrange还是一样的效果"
    for i in xrange(1,10,1):     #还是只能执行9次,和其他语言的 i=1 to 10 可执行10次是不同的
        print 'i=:', i    
        
    print 'for i in range(1,1)这样是不会进入循环的'
    print "而其他语言的 for i=1 to 1 是可以进入一次循环的"
    for i in range(1,1):     # 也就是说这样是不会进入循环的。
        print '没执行这里:i=:', i
    print "所以,要执行定次数循环必须将range(1,1)的第二个数字加1"
    
    print "for实现step效果递增"
    for i in xrange(0,10,2):
        print(i)
    
    print "for实现step效果递减"
    for i in xrange(10,0,-2):
        print(i)
    

    输出结果为:

    for循环只能执行range内两数字相减次数
    i=: 1
    i=: 2
    i=: 3
    i=: 4
    i=: 5
    i=: 6
    i=: 7
    i=: 8
    i=: 9
    使用xrange还是一样的效果
    i=: 1
    i=: 2
    i=: 3
    i=: 4
    i=: 5
    i=: 6
    i=: 7
    i=: 8
    i=: 9
    for i in range(1,1)这样是不会进入循环的
    而其他语言的 for i=1 to 1 是可以进入一次循环的
    所以,要执行定次数循环必须将range(1,1)的第二个数字加1
    for实现step效果递增
    0
    2
    4
    6
    8
    for实现step效果递减
    10
    8
    6
    4
    2
    
    冷火

       冷火

      jes***[email protected]

    9年前 (2018-06-27)
  9. #0

       公子留仙

      187***[email protected]

    15

    输出各种形状三角形:

    #coding=UTF-8
    rows = int(input('输入列数: '))
    print "用for函数书写的正等腰直角三角形"
    for i in range(0, rows):
        for k in range(0, i+1):
            print " * ",
        print "\n"
    print "用for函数书写的倒等腰直角三角形"
    for i in range(0, rows):
        for k in range(0, rows-i):
            print " * ",
        print "\n"
    print "用while函数书写的正等腰直角三角形"
    i=1
    while i:
        j=1
        while j:
            print "*"," ",
            if i==j:
                break
            j+=1
            if j>rows:
               break
        print "\n"
        i+=1
        if i>rows:
            break
    公子留仙

       公子留仙

      187***[email protected]

    8年前 (2018-12-27)
  10. #0

       SUNBIRDS

      292***[email protected]

    22

    输入区间,求取区间内的质数,看着大家都在做笔记,我也留一个吧。

    a = []
    #需要输入2个整数,用来确定求质数的范围
    start =int( input("请输入你想要的求取质数范围开始值:"))
    end1 = int(input("请输入你想要的求取质数范围结束值:"))
    for num in range(start,end1):
        j = 0
        for i in range(2,num):
            if num % i == 0:
                print("%d = %d * %d" % (num,num/i,i))
                
                break
                #pass
        else:
            print(num,"是一个质数")
            a.append(num)
        
    print("--------已经都存起来了----------")  
    print(a)  
    SUNBIRDS

       SUNBIRDS

      292***[email protected]

    6年前 (2021-01-18)

点我分享笔记

取消

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址
分类导航
  • Python / 数据科学
    • Python 教程
    • Python2.x 教程
    • FastAPI 教程
    • Flask 教程
    • Django 教程
    • NumPy 教程
    • Pandas 教程
    • SciPy 教程
    • Matplotlib 教程
    • Dash 教程
    • Jupyter Notebook 教程
    • Pillow 教程
    • 量化交易
    • R 教程
    • Julia 教程
  • AI / 智能开发
    • AI Agent(智能体)
    • AI(人工智能)
    • AI 应用案例
    • Codex 教程
    • Vibe Coding 教程
    • Claude Code
    • OpenCode
    • Skills(技能)
    • Ollama 教程
    • Hermes Agent
    • DeepSeek Harness
    • Pi Agent
    • AI 数学基础
    • TensorFlow 教程
    • PyTorch 教程
    • Scikit-learn 教程
    • 机器 教程
    • LangChain
    • 自然语言处理 NLP
    • OpenCV 教程
    • Selenium 教程
    • Playwright 教程
  • 前端开发
    • HTML 教程
    • HTML5 教程
    • CSS 教程
    • CSS3 教程
    • JavaScript 教程
    • HTML DOM 教程
    • TypeScript 教程
    • AJAX 教程
    • JSON 教程
    • Tailwind CSS 教程
    • Bootstrap4 教程
    • Bootstrap5 教程
    • Foundation 教程
    • Vue.js 教程
    • Vue3 教程
    • React 教程
    • Next.js 教程
    • Three.js 教程
    • AngularJS 教程
    • Angular 教程
    • jQuery 教程
    • jQuery UI 教程
    • jQuery EasyUI 教程
    • ECharts 教程
    • Chart.js 教程
    • Highcharts 教程
    • Google 地图 教程
    • SVG 教程
    • Font Awesome 教程
  • 后端开发
    • Node.js 教程
    • Electron 教程
    • PHP 教程
    • Java 教程
    • Go 教程
    • Rust 教程
    • C# 教程
    • Unity 教程
    • Servlet 教程
    • JSP 教程
    • ASP 教程
    • AppML 教程
    • VBScript 教程
    • Swagger 教程
    • RESTful API 教程
    • Docker 教程
    • Linux 教程
    • ZooKeeper 教程
  • 数据库
    • SQL 教程
    • MySQL 教程
    • PostgreSQL 教程
    • SQLite 教程
    • MongoDB 教程
    • Redis 教程
    • Memcached 教程
  • 移动开发
    • Android 教程
    • Flutter 教程
    • Ionic 教程
    • jQuery Mobile 教程
    • Swift 教程
    • Kotlin 教程
  • DevOps / 工程化
    • Git 教程
    • SVN 教程
    • CMake 教程
    • Maven 教程
    • VS Code 教程
    • Obsidian 教程
    • PyCharm 教程
    • Eclipse 教程
    • Markdown 教程
    • LaTeX 教程
  • 编程语言
    • C 教程
    • C++ 教程
    • Zig 教程
    • Scala 教程
    • Ruby 教程
    • Perl 教程
    • Lua 教程
    • Dart 教程
    • 汇编语言 教程
    • Verilog 教程
  • 计算机基础
    • 计算机组成原理
    • 数据结构与算法
    • C 语言数据结构与算法
    • 设计模式
    • Python 设计模式
    • 正则表达式
    • HTTP 教程
    • TCP/IP 教程
    • 网络协议
    • W3C 教程
  • XML / Web Service
    • XML 教程
    • DTD 教程
    • XML DOM 教程
    • XSLT 教程
    • XPath 教程
    • XQuery 教程
    • XLink 教程
    • XPointer 教程
    • XML Schema 教程
    • XSL-FO 教程
    • Web Service 教程
    • WSDL 教程
    • SOAP 教程
    • RSS 教程
    • RDF 教程
  • .NET
    • ASP.NET 教程
    • MVC 教程
    • Razor 教程
    • Web Forms 教程
    • Web Pages 教程
    • PowerShell 教程
  • 网站建设
    • 网站建设指南
    • 浏览器信息
    • 网站主机教程
    • 网站品质

字节 Coding Plan 限时 9.9 元起,支持 Deepseek-V4、GLM-5.3、Doubao-Seed-Evolving、Kimi-K3。
百度 Dumate 百度推出的桌面级 AI 智能体。 输入激活码送 4000 积分
使用文档
Trae AI 原生开发环境,让编程更高效。新用户注册赠2500积分,管理项目,也交付成果。
Advertisement
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.