条件语句(if/elif/else)
您好,欢迎来到 GDScript 基础教程系列。
在这一集中,我将介绍条件语句(if/elif/else)。
定义
在编程中,条件语句是编程语言的特征,它根据程序员指定的布尔条件计算为真或假来执行不同的计算或操作。
通俗地说,有时程序员希望根据我们从代码中获得的其他决策或结果来执行不同的代码操作。
GDScript 有哪些类型的条件语句?
在 GDScript 中有两种不同的方法可以处理条件语句:
- if/elif/else 语句
- 匹配语句
if 关键字
使用if关键字指定在条件为真时运行的代码块:
如果条件为假,则跳过代码块。if 2 > 1:
# run everything inside the block of code
if 2 < 1:
# Block of code never runs
else 关键字
else如果 if 语句条件为假,则使用关键字运行代码块:
在这种情况下,因为整数值 1 永远不会大于 2,else 语句将始终运行。if 2 < 1:
# Block of code never runs
else:
# Block of code runs
elif 关键字
有时我们想在到达 else 关键字之前针对多个条件进行测试。
为此,我们使用elif关键字。
elif只要 if 语句中的条件为假,该关键字就会运行。
您还可以将多个 elif 关键字链接在一起:if 2 < 1:
# Block of code never runs
elif 2 > 1:
# Block of code runs
请记住,一个 if 语句链中只能有一个if关键字和一个else关键字。# An if statement chain
if 1 < 2:
# block of code
elif 1 < 3:
# block of code
elif 1 < 4:
# block of code
else:
# run code
猜猜这里发生了什么
```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”) ```