条件语句(if/elif/else)

您好,欢迎来到 GDScript 基础教程系列。
在这一集中,我将介绍条件语句(if/elif/else)。

定义

在编程中,条件语句是编程语言的特征,它根据程序员指定的布尔条件计算为真或假来执行不同的计算或操作。
通俗地说,有时程序员希望根据我们从代码中获得的其他决策或结果来执行不同的代码操作。

GDScript 有哪些类型的条件语句?

在 GDScript 中有两种不同的方法可以处理条件语句:

  • if/elif/else 语句
  • 匹配语句

    if 关键字

    使用if关键字指定在条件为真时运行的代码块:
    1. if 2 > 1:
    2. # run everything inside the block of code
    如果条件为假,则跳过代码块。
    1. if 2 < 1:
    2. # Block of code never runs

    else 关键字

    else如果 if 语句条件为假,则使用关键字运行代码块:
    1. if 2 < 1:
    2. # Block of code never runs
    3. else:
    4. # Block of code runs
    在这种情况下,因为整数值 1 永远不会大于 2,else 语句将始终运行。

    elif 关键字

    有时我们想在到达 else 关键字之前针对多个条件进行测试。
    为此,我们使用elif关键字。
    elif只要 if 语句中的条件为假,该关键字就会运行。
    1. if 2 < 1:
    2. # Block of code never runs
    3. elif 2 > 1:
    4. # Block of code runs
    您还可以将多个 elif 关键字链接在一起:
    1. # An if statement chain
    2. if 1 < 2:
    3. # block of code
    4. elif 1 < 3:
    5. # block of code
    6. elif 1 < 4:
    7. # block of code
    8. else:
    9. # run code
    请记住,一个 if 语句链中只能有一个if关键字和一个else关键字。

    猜猜这里发生了什么

    ```swift var health: int = 100

if health >= 100: print(“Full Health”)

elif health > 60: print(“Health is Good”)

elif health > 30: print(“Health is low”)

elif health >= 1: print(“Health is dangerously low”)

else: print(“Health is depleted”) ```