I’m trying to format a little programming joke about a variable called goingToTurnSentient. What would a basic if-else version look like, and is there a simpler way to write it?
How would you write this simple if-else bit of code?
Answers
In a C-style language, the conditional version could look like this:
if (goingToTurnSentient) { goingToTurnSentient = false; } else { // Nothing happens }
The braces mark the parts controlled by the condition. The exact syntax varies by language, though.
Reply to this answer
If both outcomes leave the variable false, the if-else is unnecessary. Just write:
goingToTurnSentient = false;
For the joke, the longer version may be funnier precisely because it is doing extra work.
Reply to this answer
In Python, the same idea uses a colon and indentation rather than braces:
if goingToTurnSentient: goingToTurnSentient = False
You can leave out the else if it has no action. Also, Python spells the Boolean value False with a capital F, while many other languages use lowercase false.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions