By naadi via Discussions on Python.org at 09Jun2022 17:22:
I was wondering if there is a shorter or more functional way to write
“while loops” in situations where you have to check multiple
conditions.
my problem is this while is way too long and it is hard to work with.while candle_riddle_ans.lower() != 'candle' and candle_riddle_ans.lower() != 'a candle' and candle_riddle_ans.lower() != 'the candle' and candle_riddle_ans.lower() != 'candles':
I’m guessing that this is difficult because of the line length. Others
have pointed out using functions for the test if the test is…
complicated.
However, if your issue is readability (a core tenet of the Zen - run the
“import this” statement), you can use brackets to extend an expression
over multiple lines, for example:
while (
candle_riddle_ans.lower() != 'candle'
and candle_riddle_ans.lower() != 'a candle'
and candle_riddle_ans.lower() != 'the candle'
and candle_riddle_ans.lower() != 'candles'
):
Also, that particular condition can be written as:
while candle_riddle_ans.lower() not in ('candle', 'a candle', 'the candle', 'candles'):
or:
while candle_riddle_ans.lower() not in (
'candle',
'a candle',
'the candle',
'candles'
):
according to your taste.
Cheers,
Cameron Simpson cs@cskk.id.au