加入 else
你只能把 else 與 if 敘述搭配使用。else 不需要條件;只要控制結構中前面的條件皆為 FALSE,對應的程式碼就會被執行。以下是使用範例:
if (condition) {
expr1
} else {
expr2
}
務必要注意:else 關鍵字要與 if 區塊的結尾右大括號在同一行!
你在前面練習中撰寫的兩個 if 敘述都已經準備好可以使用。現在就交給你把它們各自擴充上合適的 else 吧!
本練習屬於課程
R 中級
練習說明
為兩個控制結構都加入一個 else,使得:
- 當
medium的 if 條件不成立時,在主控台列印出「Unknown medium」。 - 當
num_views的 if 條件不成立時,R 會列印出「Try to be more visible!」。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Variables related to your last day of recordings
medium <- "LinkedIn"
num_views <- 14
# Control structure for medium
if (medium == "LinkedIn") {
print("Showing LinkedIn information")
}
# Control structure for num_views
if (num_views > 15) {
print("You're popular!")
}