One or Another explainer

The aim of this puzzle: Use an if-else statement to print out whether the number is 1 or something else.

Walkthrough of the solution: An if-else statement is really just a regular if statement with another set of curly brackets. That second block {} of code will only run if the code in the if statement parentheses is false. So, the if statement checks the parentheses and if it’s true the first code block runs, and if it’s false the second code block runs. Only one will run, not both or neither.

In this puzzle, there are only two categories that the number can be: 1 or "not 1".

If it’s 2 or 3, then it is "not 1". That means we can just check if the number is ‘1’ in the if statement and if it doesn’t pass the test, the else block will run and we know the number is either 2 or 3. So in the else block, we just need to add a print() call with a string that says, “It is not 1”.

Sample code solution:
(Tap below to reveal)

var number = pickRandom(3);
print(number);

if (number === 1) {
  print('It is 1');
} else {
  print('It is not 1');
}

JavaScript Concepts: Binary Expression (===), Calling Functions, Conditionals (if-else statement), Identifiers, Variable Declaration
Grasshopper Concepts: pickRandom(), print()

2 Likes

If number is pick random, why is number 3 placed inside the ()?

And how comes dat we see only 1, 2 and 3 and not other numbers when we play the code?

Is there a hidden code that we do not see?

Hey there,

If pickRandom() is called with an array, like this: pickRandom(['cat', 'dog', 'toad']), it will pick a random element in the array.

If pickRandom() is called with a single number, it will randomly choose a number between 0 and that number. For example, pickRandom(5) chooses a random number between 0 and 5.

Hope this helps!
Ben

1 Like

Thank you for your help :grinning: