3 ms·
I'm slow this morning. That took me a couple of minutes to get the example. 'foo = 42 and foo / 2' I was expecting an undefined variable since foo was never
by jim_h 16y ago
I'm slow this morning. That took me a couple of minutes to get the example.
'foo = 42 and foo / 2'
I was expecting an undefined variable since foo was never set because I was thinking of it as foo = (42 and foo / 2)
Basically I would write the example as this in 2 lines to avoid confusion and not use 'and':
foo = 42
foo / 2
Maybe another example in the article would have been better to show the power of 'and'.
- avdi 16y agoWriting it in two lines would defeat the purpose of demonstrating the difference between && and 'and'.
- CodeMage 16y agoYep, that's an important point: you should probably have chosen a different example. The one you used will either make people say "it's a lot better to write it in two lines" or "oh, cool, I can write one liners like that". Your post is explaining and demonstrating the use of "and" and "or", whose purpose is to allow idioms which rely on short-circuiting logic to control side effects, but that particular example didn't involve side effects after the operator (which is the whole point). Perhaps it would be a good idea to replace that example with one that shows what would happen if you used "and" in an "if". It would serve the same purpose as the one you have currently -- show the unintended effects of using the wrong flavor of operator -- without confusing people or unintentionally teaching bad practices.
- stevejohnson 16y agoI agree that the numeric example in the blog post was a bad one. The use of 'and' just looks confusing in that situation. You might try something like "foo = open_connection() and send_data()" instead.