I found another solution but need more explanations about their differences

Hello everybody,

I found another solution for this challenge using the exclamation mark. By coming back to the game window everything seems to work perfectly.

Can anyone explains me when using ‘else’ statement is better than the exclamation mark solution ?
In both cases we end up with four lines of code, it’s not shorter but there must be a reason :thinking: What do you think ?

Thanks

Capture d'écran_20221125_012308

1 Like

Using else is kinda like an ‘or’ question:

The approach you used would be two separate questions

As you can see, the first method is far more efficient since you are asking a single question and getting the exact same result from asking 2 questions. That’s what else statements are for, to prevent code from running when the first if statement already met the condition.

Does this mean you should always use else statements? The answer to that is, no. Using the same question analogy, sometimes you want to ask completely unrelated questions.

Using else statements:

Using two separated if statements:

It all comes down to what you are trying to achieve with your code and if the two code blocks can/should run right after the other.

In this case, since you cannot have a button down and up at the same time (unless it’s a quantic button or something weird thing like that), the better approach is to use an else statement.

Hope this helps!

1 Like

Thank you very much @Yee! It helps a lot and your examples are perfect to understand. Thank you :slightly_smiling_face:

1 Like

@Yee explained it nicely. else is like a ‘catch all’ for whatever didn’t match the if (or else if) bits

With the ‘not’ operator (exclamation) you are usually not catching all. In your case you will be

Because you are checking the same thing for both states you are essentially catching all.

In some situations, the state may change inside an if and then your solution would break. Here’s a silly, made-up example of which some variation may very well appear in the real world

int someNumber = GetSomeNumber();

if (someNumber == 0)
{
    MakeBackgroundGreen();
    someNumber++;
}
else
{
    MakeBackgroundRed();
}

In the above, the background will be green if GetSomeNumber() returned 0, and red if it returned anything else

int someNumber = GetSomeNumber();

if (someNumber == 0)
{
    MakeBackgroundGreen();
    someNumber++;
}

if (someNumber != 0)
{
    MakeBackgroundRed();
}

In this one, the background will never be green, even if GetSomeNumber() returned 0. So, like @Yee said;

2 Likes

Thank you @bixarrio for these details :slightly_smiling_face:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.