Menu
CoddyTech

if-else 语句

本课属于 Coddy Ruby 学习旅程的“基础知识”单元。第 22 课,共 88 课。

有时,你需要让程序在两条不同的路径中做出选择。else 关键字可以让你指定 if 条件为 false 时应该发生什么:

age = 15

if age >= 18
  puts "You can vote!"
else
  puts "You're too young to vote."
end

在这个示例中,由于 age 是 15,条件 age >= 18 为假,因此 Ruby 会跳过第一个代码块,改为运行 else 后面的代码。程序会输出 "You're too young to vote."

使用 if-else 时,两个代码块中始终只有一个会运行。如果条件为真,第一个代码块会执行。如果条件为假,第二个代码块会执行:

balance = 100
withdrawal = 150

if balance >= withdrawal
  puts "Withdrawal successful"
else
  puts "Insufficient funds"
end

当你有两个互斥的结果时,这种结构非常合适。程序必须选择其中一种结果,不能两种都选,也不能两种都不选。

challenge icon

挑战

简单

已为你提供以下变量:

temperature = 35
has_umbrella = false
account_balance = 50
withdrawal_amount = 75
player_score = 100
high_score = 100

使用 if-else 语句判断下面的每种情况。根据条件为真还是为假,打印相应的消息。

  1. 如果 temperature 大于 30,打印 It's hot outside。否则,打印 The weather is nice。
  2. 如果 has_umbrella 是 true,打印 You're prepared for rain。否则,打印 You might get wet。
  3. 如果 account_balance 大于或等于 withdrawal_amount,打印 Withdrawal approved。否则,打印 Insufficient funds。
  4. 如果 player_score 大于 high_score,打印 New high score!。否则,打印 Try again。
  5. 如果 temperature 小于 0,或者 temperature 大于 40,打印 Extreme weather。否则,打印 Normal conditions。

每条消息都应单独占一行。

亲手试试

# 变量已经为你定义好了
temperature = 35
has_umbrella = false
account_balance = 50
withdrawal_amount = 75
player_score = 100
high_score = 100

# TODO:在下方编写代码
# 使用 if-else 语句判断每种情况,并打印相应的消息
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: Ruby 在线编译器