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 While 循环语句 | 菜鸟教程

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

  • 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 条件语句
Python for 循环语句

Python While 循环语句

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

while 判断条件(condition):
    执行语句(statements)……

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。

当判断条件假 false 时,循环结束。

执行流程图如下:

Gif 演示 Python while 语句执行过程

复杂一点:

实例

#!/usr/bin/python count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"

运行实例 »

以上代码执行输出结果:

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立,具体用法如下:

# continue 和 break 用法 i = 1 while i < 10: i += 1 if i%2 > 0: # 非双数时跳过输出 continue print i # 输出双数2、4、6、8、10 i = 1 while 1: # 循环条件为1必定成立 print i # 输出1~10 i += 1 if i > 10: # 当i大于10时跳出循环 break


无限循环

如果条件判断语句永远为 true,循环将会无限的执行下去,如下实例:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- var = 1 while var == 1 : # 该条件永远为true,循环将无限执行下去 num = raw_input("Enter a number :") print "You entered: ", num print "Good bye!"

以上实例输出结果:

Enter a number  :20
You entered:  20
Enter a number  :29
You entered:  29
Enter a number  :3
You entered:  3
Enter a number between :Traceback (most recent call last):
  File "test.py", line 5, in <module>
    num = raw_input("Enter a number :")
KeyboardInterrupt

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。



循环使用 else 语句

在 python 中,while … else 在循环条件为 false 时执行 else 语句块:

实例

#!/usr/bin/python count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5"

以上实例输出结果为:

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5


简单语句组

类似 if 语句的语法,如果你的 while 循环体中只有一条语句,你可以将该语句与while写在同一行中, 如下所示:

实例

#!/usr/bin/python flag = 1 while (flag): print 'Given flag is really true!' print "Good bye!"

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。

AI 思考中...
Python 条件语句
Python for 循环语句

6 篇笔记 写笔记

  1. #0

       我是可爱男生睡便天下男人

      col***[email protected]

    141

    猜大小的游戏

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import random
    s = int(random.uniform(1,10))
    #print(s)
    m = int(input('输入整数:'))
    while m != s:
        if m > s:
            print('大了')
            m = int(input('输入整数:'))
        if m < s:
            print('小了')
            m = int(input('输入整数:'))
        if m == s:
            print('OK')
            break;
    
    我是可爱男生睡便天下男人

       我是可爱男生睡便天下男人

      col***[email protected]

    10年前 (2017-04-18)
  2. #0

       六月耶

      438***@qq.com

    85

    猜拳小游戏

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import random
    while 1:
        s = int(random.randint(1, 3))
        if s == 1:
            ind = "石头"
        elif s == 2:
            ind = "剪子"
        elif s == 3:
            ind = "布"
        m = raw_input('输入 石头、剪子、布,输入"end"结束游戏:')
        blist = ['石头', "剪子", "布"]
        if (m not in blist) and (m != 'end'):
            print "输入错误,请重新输入!"
        elif (m not in blist) and (m == 'end'):
            print "\n游戏退出中..."
            break
        elif m == ind :
            print "电脑出了: " + ind + ",平局!"
        elif (m == '石头' and ind =='剪子') or (m == '剪子' and ind =='布') or (m == '布' and ind =='石头'):
            print "电脑出了: " + ind +",你赢了!"
        elif (m == '石头' and ind =='布') or (m == '剪子' and ind =='石头') or (m == '布' and ind =='剪子'):
            print "电脑出了: " + ind +",你输了!"
    

    测试结果:

    输入 石头、剪子、布,输入"end"结束游戏:石头
    电脑出了: 石头,平局!
    输入 石头、剪子、布,输入"end"结束游戏:石头    
    电脑出了: 剪子,你赢了!
    输入 石头、剪子、布,输入"end"结束游戏:
    
    六月耶

       六月耶

      438***@qq.com

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

       夕阳晨伤

      112***[email protected]

    38

    摇筛子游戏

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    import random
    import sys
    import time
    
    result = []
    while True:
        result.append(int(random.uniform(1,7)))
        result.append(int(random.uniform(1,7)))
        result.append(int(random.uniform(1,7)))
        print result
        count = 0
        index = 2
        pointStr = ""
        while index >= 0:
            currPoint = result[index]
            count += currPoint
            index -= 1
            pointStr += " "
            pointStr += str(currPoint)
        if count <= 11:
            sys.stdout.write(pointStr + " -> " + "小" + "\n")
            time.sleep( 1 )   # 睡眠一秒
        else:
            sys.stdout.write(pointStr + " -> " + "大" + "\n")
            time.sleep( 1 )   # 睡眠一秒
        result = []
    
    夕阳晨伤

       夕阳晨伤

      112***[email protected]

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

       (+__+)

      lk0***[email protected]

    19

    十进制转二进制

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    denum = input("输入十进制数:")
    print denum,"(10)",
    binnum = []
    # 二进制数
    while denum > 0:
        binnum.append(str(denum % 2)) # 栈压入
        denum //= 2
    print '= ',
    while len(binnum)>0:
        import sys
        sys.stdout.write(binnum.pop()) # 无空格输出print ' (2)'
    (+__+)

       (+__+)

      lk0***[email protected]

    9年前 (2017-07-25)
  5. #0

       九九乘法表

      690***[email protected]

    26

    while循环 - 九九乘法表

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    #九九乘法表
    
    i = 1
    while i :
        j = 1
        while j:
            print j ,"*", i ," = " , i * j , '  ',
            if i == j :
                break
    
            j += 1
            if j >= 10:
                break
        
        print "\n"
        i += 1
        if i >= 10:
            break
    九九乘法表

       九九乘法表

      690***[email protected]

    9年前 (2017-09-14)
  6. #0

       流风回雪

      145***[email protected]

    46

    Pyhton 去除字符串首尾的空格:

    def trim(s):
        while s[:1] == ' ':
            s = s[1:]
        while s[-1:] == ' ':
            s = s[:-1]
        return s
    
    str = '   Runoob     '
    print(trim(str))
    流风回雪

       流风回雪

      145***[email protected]

    9年前 (2018-04-07)

点我分享笔记

取消

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址
分类导航
  • 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.