If () Then, Else | |
if <> then{ } else{ } :: control | |
Category | Control |
Type | C |
Introduced in | 16Dec05 (0.x) |
The if () then, else block is a control block and a C block. (It is also sometimes known as an "E" block.) The block checks its boolean condition; if the condition is true, the code held inside the first C (space) will activate; if the condition is false, the code inside the second C will activate.
Prior to Scratch 2.0, this block was known as If (), Else, or
if <>{ }else{ }::control
Example Uses
In programming, a very important part is checking conditions. In Scratch, 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:
- Doing the opposite action of the first action if the condition is false
repeat until <touching (edge v)?> if <(mouse x) > [0]> then move (1) steps else move (-1) steps end end
- If a Sprite's health is below a certain amount, it dies, otherwise it does something else
when green flag clicked forever if <(health) = [0]> then play sound (Failure v) until done stop [all v] else broadcast (attack v) end
- Easy script changes — if a variable equals a certain value, one thing happens, and if the variable does not equal the value, a different thing happens
if <(answer) = [5]> then say [Correct!] for (2) seconds else play sound (failed task v) until done stop [all v] end
- Scripts that are adaptable to changes in conditions (such as a changing variable)
if <touching color [#7092be]?> then say [We found water!] else say [ ] end
Workaround
- Main article: List of Block Workarounds
This block can be replicated with the following code:
if <. . .::grey> then . . . //condition=true end if <not <. . .::grey> > then . . . //condition=false end
or
if <. . .::grey> then . . .::grey broadcast (continue v) stop [this script v] end . . .::grey broadcast (continue v)
Note that this last workaround only works if the condition will not be negated in the middle of the first If () block.
Suggestions
Scratchers have suggested a block that reports the first input if true, otherwise if false, reports the second input.[1]
if <> then [] else []:: operators reporter
This block does exist in some Scratch modifications, such as Snap!. However, it can be worked around with the following code, which only works for numbers:
((true::grey)*<boolean::grey>)+((false::grey)*<not<boolean::grey>>)
or this one, which works for any argument type:
if <boolean::grey> then set [report v] to (true::grey) else set [report v] to (false::grey) end