GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.runoob.com — Python3 条件控制 | 菜鸟教程
Python 3 教程
Python3 教程
Python3 简介
Python3 环境搭建
Python3 Pycharm
Python3 VScode
Python3 基础语法
Python3 基本数据类型
Python3 数据类型转换
Python3 解释器
Python3 注释
Python3 运算符
Python3 数字(Number)
Python3 字符串
Python3 列表
Python3 元组
Python3 字典
Python3 集合
Python3 条件控制
Python3 循环语句
Python3 编程第一步
Python3 推导式
Python3 迭代器与生成器
Python3 with
Python3 函数
Python3 lambda
Python3 装饰器
Python3 数据结构
Python3 模块
Python __name__
Python3 输入和输出
Python3 File
Python3 OS
Python3 错误和异常
Python3 面向对象
Python3 命名空间/作用域
Python 虚拟环境的创建
Python 类型注解
Python3 标准库概览
Python3 实例
Python 测验
Python3 高级教程Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQtPython3 条件控制Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。 可以通过下图来简单了解条件语句的执行过程: 代码执行过程:
条件判断关键字
if 语句Python中if语句的一般形式如下所示: if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。 注意:
Gif 演示:
实例以下是一个简单的 if 实例: 实例#!/usr/bin/python3
var1 = 100
if var1:
print ("1 - if 表达式条件为 true")
print (var1)
var2 = 0
if var2:
print ("2 - if 表达式条件为 true")
print (var2)
print ("Good bye!")
执行以上代码,输出结果为: 1 - if 表达式条件为 true 100 Good bye! 从结果可以看到由于变量 var2 为 0,所以对应的 if 内的语句没有执行。 以下实例演示了狗的年龄计算判断: 实例#!/usr/bin/python3
age = int(input("请输入你家狗狗的年龄: "))
print("")
if age <= 0:
print("你是在逗我吧!")
elif age == 1:
print("相当于 14 岁的人。")
elif age == 2:
print("相当于 22 岁的人。")
elif age > 2:
human = 22 + (age -2)*5
print("对应人类年龄: ", human)
### 退出提示
input("点击 enter 键退出")
将以上脚本保存在dog.py文件中,并执行该脚本: $ python3 dog.py 请输入你家狗狗的年龄: 1 相当于 14 岁的人。 点击 enter 键退出 以下为if中常用的操作运算符:
实例#!/usr/bin/python3
# 程序演示了 == 操作符
# 使用数字
print(5 == 6)
# 使用变量
x = 5
y = 8
print(x == y)
以上实例输出结果: False False high_low.py文件演示了数字的比较运算: 实例#!/usr/bin/python3
# 该实例演示了数字猜谜游戏
number = 7
guess = -1
print("数字猜谜游戏!")
while guess != number:
guess = int(input("请输入你猜的数字:"))
if guess == number:
print("恭喜,你猜对了!")
elif guess < number:
print("猜的数字小了...")
elif guess > number:
print("猜的数字大了...")
执行以上脚本,实例输出结果如下: $ python3 high_low.py 数字猜谜游戏! 请输入你猜的数字:1 猜的数字小了... 请输入你猜的数字:9 猜的数字大了... 请输入你猜的数字:7 恭喜,你猜对了! if 嵌套在嵌套 if 语句中,可以把 if...elif...else 结构放在另外一个 if...elif...else 结构中。 if 表达式1:
语句
if 表达式2:
语句
elif 表达式3:
语句
else:
语句
elif 表达式4:
语句
else:
语句
实例# !/usr/bin/python3
num=int(input("输入一个数字:"))
if num%2==0:
if num%3==0:
print ("你输入的数字可以整除 2 和 3")
else:
print ("你输入的数字可以整除 2,但不能整除 3")
else:
if num%3==0:
print ("你输入的数字可以整除 3,但不能整除 2")
else:
print ("你输入的数字不能整除 2 和 3")
将以上程序保存到 test_if.py 文件中,执行后输出结果为: $ python3 test.py 输入一个数字:6 你输入的数字可以整除 2 和 3 match...casePython 3.10 增加了 match...case 的条件判断,不需要再使用一连串的 if-else 来判断了。 match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_ 可以匹配一切。 语法格式如下: match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>case _: 类似于 C 和 Java 中的 default:,当其他 case 都无法匹配时,匹配这条,保证永远会匹配成功。 实例
def http_error(status): match status: case 400: return "Bad request" case 404: return "Not found" case 418: return "I'm a teapot" case _: return "Something's wrong with the internet" print(http_error(400)) print(http_error(404)) print(http_error(418)) print(http_error(500)) 以上是一个输出 HTTP 状态码的实例,多个状态码的输出结果为: Bad request Not found I'm a teapot Something's wrong with the internet 一个 case 也可以设置多个匹配条件,条件使用 | 隔开,例如: ...
case 401|403|404:
return "Not allowed"
实例
def check_permission(status): match status: case 200: return "OK - 请求成功" case 301 | 302: return "Redirect - 重定向" case 401 | 403 | 404: return "Not allowed - 无权限或未找到" case 500 | 502 | 503: return "Server Error - 服务器错误" case _: return "Unknown status - 未知状态码" for code in [200, 301, 403, 500, 418]: print(f"状态码 {code}: {check_permission(code)}") match...case 更多内容参考:Python match-case 语句
AI 思考中...
|
| 类型 | False | True |
|---|---|---|
| 布尔 | False(与0等价) | True(与1等价) |
| 数值 | 0, 0.0 | 非零的数值 |
| 字符串 | '', ""(空字符串) | 非空字符串 |
| 容器 | [], (), {}, set() | 至少有一个元素的容器对象 |
| None | None | 非None对象 |
Yuanlgone
183***[email protected]
if 的两种格式:
可以括号限定代码域,加强代码可读性。
name ="pag"
if name == "pag":
print(name=="pag") # True
if (name == "pag"):{
print(name == "pag") # True
}
来着 As000000 的解读:
if 可以括号限定代码域,加强代码可读性。
这种说法是不正确的,python 代码块只有缩进。
不妨把花括号里面多加一行,就发现会报错:
if (name == "pag"):{ print(name == "pag") print("line 2 of if condition") }报错信息:
File "test.py", line 4 print("line 2 of if condition") ^ SyntaxError: invalid syntax而 if 后花括号一条 print 语句之所以没报错,是因为花括号括起来的是一个集合,相当于条件为 True 的时候定义一个集合,我们不妨以相似的方式定义两个集合 aa,bb。
name = "pag" aa={print(name == "pag")} bb={print(name == "pag"),"BBBB"} print(aa) print(bb)输出结果如下:
True True {None} {'BBBB', None}
Yuanlgone
183***[email protected]
存在时间
tsj***[email protected]
取随机数扩展。取随机数直到两数相等,显示取数次数。
import random
x = random.choice(range(100))
y = random.choice(range(100))
b,c = x,y
a = 1
print(x,y)
while x != y:
if x > y:
print('x:',x)
elif x == y:
print('x+y:', x + y,'totall cal ',a,'times')
else:
print('y:',y)
x = random.choice(range(100))
y = random.choice(range(100))
a = a+1
print('initialized data:',b,c,'x+y:', x + y,'total cal ',a,'times')存在时间
tsj***[email protected]
川河岳
cit***[email protected]
存在时间 楼上的太复杂了,而且 elif 还不会执行到,优化如下:
import random
a = 0
while True:
x = random.choice(range(100))
y = random.choice(range(100))
a = a+1
if x > y:
print(x,'>',y)
elif x < y:
print(x,'<',y)
else:
print('x=y=', x, 'total cal ', a, 'times')
break川河岳
cit***[email protected]
葫芦又
111***[email protected]
如果 if 语句中的条件过长,可以用接续符 \ 来换行。
例如:
if 2>1 and 3>2 and 4>3 and \
5>4 and 6>5 and 7>6 and \
8>7:
print("OK")
注意: \ 后的一行要缩进没有要求,可无序缩进,但我们保持代码的可读性一般设置同样的缩进格式。
葫芦又
111***[email protected]
秋 | 先生
mas***[email protected]
实例:
# 查询 n 到 m 间的所有素数
def find_prime_number(n, m):
if isinstance(n, int) and isinstance(m, int):
if m <= 1:
return "error range"
if 1 >= n > m:
return "error start"
numbers = list()
num = n
while num <= m:
i = 2
while i < num:
if (num % i == 0) and (num != i):
break
else:
i += 1
if num == i:
numbers.append(num)
num += 1
return numbers
else:
return "error input"
print(find_prime_number(1, 100))秋 | 先生
mas***[email protected]
My_Skity
719***[email protected]
在 if...elif...else 的多个语句块中只会执行一个语句块,例如:
age = int(input("请输入你家狗狗的年龄: "))
print("")
if age <= 0:
print("你是在逗我吧!")
elif 1 <= age <=2: #与下一个elif条件重复,只执行符合条件的第一个语句块
print("相当于 14 岁的人。")
elif age == 2:
print("相当于 22 岁的人。")
elif age > 2:
human = 22 + (age - 2) * 5 print("对应人类年龄: ", human)
因此,在写 elif 条件时一定要做到互不重复。
My_Skity
719***[email protected]
洋洋涵
wan***[email protected]
match ... case 是 Python 3.10 中引入的一个新特性,也被称为“模式匹配”或“结构化匹配”。
它为 Python 带来了更强大、更易读的分支控制,相比于传统的 if-elif-else 链。
基本模式匹配
x = 10
match x:
case 10:
print("x is 10")
case 20:
print("x is 20")
case _:
print("x is something else")
在这里,_是一个特殊的“占位符”模式,用于匹配任何值(类似于 else)。
序列模式匹配
point = (2, 3)
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Point is on the Y axis at {y}")
case (x, 0):
print(f"Point is on the X axis at {x}")
case (x, y):
print(f"Point is at ({x}, {y})")
case _:
print("Not a point")
对象模式匹配
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(0, 3)
match p:
case Point(x=0, y=y):
print(f"Point is on the Y axis at {y}")
case Point(x=x, y=0):
print(f"Point is on the X axis at {x}")
case Point(x, y):
print(f"Point is at ({x}, {y})")
case _:
print("Not a point")
OR 模式
使用 | 来表示一个或多个模式。
x = 2
match x:
case 1 | 2 | 3:
print("x is 1, 2, or 3")
case _:
print("x is something else")
守卫
你可以使用 if 在模式匹配中添加额外的条件。
x = 10
match x:
case x if x > 5:
print("x is greater than 5")
case _:
print("x is 5 or less")洋洋涵
wan***[email protected]
取消