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 条件语句 | 菜鸟教程

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

  • 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 While 循环语句

Python 条件语句

Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。

可以通过下图来简单了解条件语句的执行过程:

Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。

Python 编程中 if 语句用于控制程序的执行,基本形式为:

if 判断条件:
    执行语句……
else:
    执行语句……

其中"判断条件"成立时(非零),则执行后面的语句,而执行内容可以多行,以缩进来区分表示同一范围。

else 为可选语句,当需要在条件不成立时执行内容则可以执行相关语句。

Gif 演示:

具体例子如下:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- # 例1:if 基本用法 flag = False name = 'luren' if name == 'python': # 判断变量是否为 python flag = True # 条件成立时设置标志为真 print 'welcome boss' # 并输出欢迎信息 else: print name # 条件不成立时输出变量名称

输出结果为:

luren            # 输出结果

if 语句的判断条件可以用>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)来表示其关系。

当判断条件为多个值时,可以使用以下形式:

if 判断条件1:
    执行语句1……
elif 判断条件2:
    执行语句2……
elif 判断条件3:
    执行语句3……
else:
    执行语句4……

实例如下:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- # 例2:elif用法 num = 5 if num == 3: # 判断num的值 print 'boss' elif num == 2: print 'user' elif num == 1: print 'worker' elif num < 0: # 值小于零时输出 print 'error' else: print 'roadman' # 条件均不成立时输出

输出结果为:

roadman        # 输出结果

由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- # 例3:if语句多个条件 num = 9 if num >= 0 and num <= 10: # 判断值是否在0~10之间 print 'hello' # 输出结果: hello num = 10 if num < 0 or num > 10: # 判断值是否在小于0或大于10 print 'hello' else: print 'undefine' # 输出结果: undefine num = 8 # 判断值是否在0~5或者10~15之间 if (num >= 0 and num <= 5) or (num >= 10 and num <= 15): print 'hello' else: print 'undefine' # 输出结果: undefine

当if有多个条件时可使用括号来区分判断的先后顺序,括号中的判断优先执行,此外 and 和 or 的优先级低于>(大于)、<(小于)等判断符号,即大于和小于在没有括号的情况下会比与或要优先判断。

简单的语句组

你也可以在同一行的位置上使用if条件判断语句,如下实例:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- var = 100 if ( var == 100 ) : print "变量 var 的值为100" print "Good bye!"

以上代码执行输出结果如下:

变量 var 的值为100
Good bye!
AI 思考中...
Python 运算符
Python While 循环语句

5 篇笔记 写笔记

  1. #0

       神仙氏族

      a72***@qq.com

    263

    python 复合布尔表达式计算采用短路规则,即如果通过前面的部分已经计算出整个表达式的值,则后面的部分不再计算。如下面的代码将正常执行不会报除零错误:

    a=0
    b=1
    if ( a > 0 ) and ( b / a > 2 ):
        print "yes"
    else :
        print "no"
    

    而下面的代码就会报错:

    a=0
    b=1
    if ( a > 0 ) or ( b / a > 2 ):
        print "yes"
    else :
        print "no"
    神仙氏族

       神仙氏族

      a72***@qq.com

    10年前 (2017-05-20)
  2. #0

       Tao

      num***[email protected]

    69
    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-
    # 一个简单的条件循环语句实现汉诺塔问题
    
    def my_print(args):
        print args
    
    def move(n, a, b, c):
        my_print ((a, '-->', c)) if n==1 else (move(n-1,a,c,b) or move(1,a,b,c) or move(n-1,b,a,c))
    
    move (3, 'a', 'b', 'c')

    更多汉诺塔问题参阅:https://www.runoob.com/w3cnote/python-tower.html

    Tao

       Tao

      num***[email protected]

    10年前 (2017-07-03)
  3. #0

       sherlockzak

      for***[email protected]

    104

    Python 没有 switch/case 语句,如果遇到很多中情况的时候,写很多的 if/else 不是很好维护,这时可以考虑用字典映射的方法替代:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import os
    def zero():
        return "zero"
    
    def one():
        return "one"
    
    def two():
        return "two"
    
    def num2Str(arg):
        switcher={
            0:zero,
            1:one,
            2:two,
            3:lambda:"three"
        }
        func=switcher.get(arg,lambda:"nothing")
        return func()
    
    if __name__ == '__main__':
        print num2Str(0)
    sherlockzak

       sherlockzak

      for***[email protected]

    9年前 (2018-03-30)
  4. #0

       John

      oyw***@126.com

    52

    if 简单条件判断一行搞定:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    a = [1,2,3]
    b = a if len(a) != 0 else ""
    print(b)
    
    c=[]
    d = c if len(c) != 0 else "c 是一个空列表"
    print(d)

    输出结果为:

    [1, 2, 3]
    c 是一个空列表
    John

       John

      oyw***@126.com

    9年前 (2018-05-22)
  5. #0

       琳琅月

      z46***[email protected]

    60

    将列表中重复的数据放在后面,返回列表中元素去除重复后的个数:

    def deduplication(nums):
        # write your code here
        exist_nums = {} 
        pointer = 0
        for num in nums:
            if num not in exist_nums:
                exist_nums[num] = True
                nums[pointer] = num
                pointer += 1
        return pointer
    print(deduplication([1,1,1,1,1,1,2,2,2,2,2,2,2,2]))
    琳琅月

       琳琅月

      z46***[email protected]

    7年前 (2019-07-13)

点我分享笔记

取消

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