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当你有两个互斥的结果时,这种结构非常合适。程序必须选择其中一种结果,不能两种都选,也不能两种都不选。
挑战
简单已为你提供以下变量:
temperature = 35
has_umbrella = false
account_balance = 50
withdrawal_amount = 75
player_score = 100
high_score = 100使用 if-else 语句判断下面的每种情况。根据条件为真还是为假,打印相应的消息。
- 如果
temperature大于30,打印It's hot outside。否则,打印The weather is nice。 - 如果
has_umbrella是true,打印You're prepared for rain。否则,打印You might get wet。 - 如果
account_balance大于或等于withdrawal_amount,打印Withdrawal approved。否则,打印Insufficient funds。 - 如果
player_score大于high_score,打印New high score!。否则,打印Try again。 - 如果
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 语句判断每种情况,并打印相应的消息这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Ruby 在线编译器