I am making a programme and I have this line of code:
self.languages = [while ans != 'no': ans = input('Insert a language you know: ')]
I hope to achieve this interaction:
Insert a language you know: English
Insert a language you know: French
Insert a language you know: no
and then self.languages will be ['English', 'French'].
But when I execute it this is the output:
self.languages = [while ans != 'no': ans = input('Insert a language you know: ')]
^^^^^
SyntaxError: invalid syntax
I also tried this:
self.languages = while ans != 'no': ans = input('Insert a language you know: ')
but it gives the same error.
What can I do?
>Solution :
There is no syntax similar to list comprehensions that uses while instead of for.
However, you can use iter in its two-argument form:
-
The first argument is a callable
fthat is executed repeatedly. -
The second argument is a sentinel value that stops the iteration if
freturns it. -
The results of the iteration (the return values of
fbefore the sentinel) are collected using thelist()constructor.
list(iter(lambda: input('Insert a language you know: '), 'no'))