From Test-Scratch-Wiki
如果 () 那么,否则 | |
如果 () 那麼 否則 | |
类别 | 控制类积木 |
形狀 | 半框形积木 |
The If () Then, Else 积木 is a 控制类积木 and a 半框形积木. The block will check its 菱形积木 condition: if the condition is true, the code held inside the first C (space) will activate, and then the script will continue; if the condition is false, the code inside the second C will activate (unlike the 如果 () 那么 block).
In Scratch 1.4, this block was named If (), Else.
用法示例
In programming, a very important part is "checking conditions"; this is done with the If () block. However, an important part of the "checking conditions" is having another piece of code that runs if the condition is false. While this may be worked around, the If (), Else block makes this simpler. Some common uses:
- Do "this" (the code inside the first C) or "that" (the code inside the second C)
重複直到 <碰到 [邊緣 v] ?> 如果 <(聲音響度) > [30]> 那麼 說出 [No loud noises.] (2) 秒 移動 (10) 點 end end
- If a 角色的 health is below a certain amount, it dies, otherwise it does something else
當 @greenflag 被點擊 重複無限次 如果 <(health) = [0]> 那麼 播放音效 [Failure v] 停止 [全部 v] 廣播訊息 [attack v] end end
- Easy 程式 changes
— if a 变量 equals a certain value, one thing happens, and if the variable does not equal the value, a different thing happens
如果 <(詢問的答案) = [5]> 那麼 說出 [Correct!] (2) 秒 播放音效 [task fail v] 到底 停止 [全部 v] end
- Scripts that are adaptable to changes in conditions (such as a changing variable)
如果 <碰到顏色 [#7092be] ?> 那麼 說出 [We found water!] 說出 [ ] end
应用
- Main article: List of Block Workarounds
This block can be replicated with the following code:
變數 [action v] 設為 (0) 如果 <condition> 那麼 變數 [action v] 設為 (1) . . . // condition=true end 如果 <(action) = (0)> 那麼 . . . // condition=false end
or
當收到訊息 [if-statement v] 如果 <condition> 那麼 . . . // condition=true 廣播訊息 [continue v] 停止 [這個程式 v] end . . . // condition=false 廣播訊息 [continue v]
當收到訊息 [continue v] . . .
or
如果 <condition> 那麼 . . . // condition=true end 如果 <<condition> 不成立> 那麼 . . . // condition=false end
Note that this last workaround only works if the condition will not be negated in the middle of the first 如果 () 那么 block.
Suggestions
Scratcher have suggested a block that reports the first input if true, otherwise if false, reports the second input.[1]
(如果 <> 那麼 [] 否則 []) // category=operators
It would be in the 运算类积木 category.