Python 的 if-else 语句用于根据条件执行不同的代码块。语法如下:if condition:条件为 true 时执行代码块else:条件为 false 时执行代码块
Python 中的 if-else 语句
在 Python 中,if-else 语句是一种条件语句,用于根据条件执行不同的代码块。
语法:
执行流程:
立即学习
“
Python免费学习笔记(深入)
”;
Python 首先评估条件。
如果条件为 True,则执行 if 块中的代码。
如果条件为 False,则执行 else 块中的代码。
if 块和 else 块是可选的。如果条件为 True,则可以省略 else 块。
示例:
Python 3.14.3
微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。
下载
此示例请求用户输入他们的年龄。如果年龄大于或等于 18,则打印消息“您已成年”。否则,打印消息“您尚未成年”。
嵌套 if-else 语句:
if-else 语句可以嵌套,以根据多个条件执行不同的代码块。
此示例首先检查用户是否已成年。如果是,它会进一步检查用户是否已达到 65 岁。如果是,则打印消息“您是老年公民”。否则,什么都不打印。
if condition:
# if condition is True, execute this block
else:
# if condition is False, execute this blockage = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
if age >= 65:
print("You are a senior citizen.")
else:
print("You are not an adult.")