0Pricing
Python For Kids · 课时

If-Else 语句

学习使用 if、else 和 elif 进行决策。

If-Else 语句 是 CoddyKit 上的免费 Python For Kids 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python For Kids 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python For Kids 课程共包含 4 节课。

使用 If-Else 做出决策

If-Else 语句

欢迎学习控制流课程!今天,我们将学习如何在 Python 程序中使用 if、else 和 elif 语句做出决策。

If-Else 语句 — 插图 1

什么是 If-Else 语句?

If-Else 语句允许程序根据特定条件选择不同的执行路径。这就像做决定一样:“如果发生这种情况,就执行那个操作;否则,就执行其他操作。”

  • If:检查条件,如果条件为真,则执行代码。
  • Else:如果 if 条件为假,则执行代码。
  • Elif:(Else If)如果前一个 if 条件为假,则检查另一个条件。

If 语句

if 语句允许程序仅在特定条件为真时执行一段代码。

语法:

if condition:
    # code to execute if condition is true

If 语句示例

让我们通过一个简单的示例,看看 if 语句是如何工作的。

示例:

# Checks if the number is positive
number = 5
if number > 0:
    print("The number is positive.")

Else 语句

else 语句允许程序在前面的 if 条件为假时执行一段代码。

语法:

if condition:
    # code to execute if condition is true
else:
    # code to execute if condition is false

If-Else 语句示例

下面介绍如何同时使用 if 和 else 语句。

示例:

# Checks if the number is even or odd
number = 4
if number % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")

Elif 语句

elif(else if 的缩写)语句允许您按顺序检查多个条件。

语法:

if condition1:
    # code to execute if condition1 is true
elif condition2:
    # code to execute if condition2 is true
else:
    # code to execute if none of the above conditions are true

If-Elif-Else 语句示例

让我们创建一个程序,将数字分类为正数、负数或零。

示例:

# Categorizes the number
number = 0
if number > 0:
    print("The number is positive.")
elif number < 0:
    print("The number is negative.")
else:
    print("The number is zero.")
age = 16
if age >= 18:
    print("You are an adult.")
elif age >= 13:
    print("You are a teenager.")
else:
    print("You are a child.")

做得很好!

您已经学会了如何使用 if、else 和 elif 语句,在 Python 程序中做出决策。这样,程序就可以根据不同条件做出不同的响应。请继续练习,创建您自己的决策程序!

If-Else 语句 — 插图 10

常见问题解答

「If-Else 语句」课时是免费的吗?

是的 — 「If-Else 语句」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python For Kids 课程的其余内容,请升级到 CoddyKit PRO。 Python For Kids 课程共包含 4 节课。

「If-Else 语句」这节课中我会学到什么?

学习使用 if、else 和 elif 进行决策。 你通过在浏览器中直接运行的动手代码来练习 Python For Kids,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Python For Kids 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Python For Kids 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「If-Else 语句」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Python For Kids 课中编写并运行代码吗?

能。每节 Python For Kids 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. If-Else 语句
  2. Python 中的循环
  3. 嵌套循环
  4. Break 与 Continue
← 返回 Python For Kids