1

Basically I need to write a program that takes input from a user and stores it in a list over and again until the word "end" is passed.

Sample Input

Spanish
dog
bowl
end

Sample Output

['spanish', 'dog', 'bowl']

This is what I have so far:

a = []
index = 0
i = 1
while i != 0:
    s = raw_input()
    if s == "end":
        i = 0
    else:
        a[index] = s
        index = index + 1
print (a)

Note that as part of the assignment, a while loop must be used.

3
  • 4
    Do you really need all the commentary about the teacher to ask this question? Commented Mar 31, 2020 at 14:08
  • Perhaps doing the official tutorial might help ? Commented Mar 31, 2020 at 14:17
  • I suppose i didn't need to include that no, my bad. Just in a bit of a hurry so wasn't thinking. Thanks for the answer! Commented Mar 31, 2020 at 14:30

3 Answers 3

4
words = []
while True:
    word = input()
    if word == 'end':
        break
    else:
        words.append(word)
print(words)

Example

Spanish
dog
bowl
end
['Spanish', 'dog', 'bowl']
Sign up to request clarification or add additional context in comments.

Comments

1

If you are using Python 3.8+, you can use this cool new feature called assignment expressions like so:

lst = []
while (answer := input('item (type "end" to exit): \t')) != 'end':
    lst.append(answer)
print(lst)

Comments

0

if you like one-line solution:

from itertools import takewhile, cycle

words = list(takewhile(lambda x: x != 'end', map(input, cycle(['type your item: ']))))

or:

words = list(takewhile(lambda x: x != 'end', map(input, cycle(['']))))
print(words)

output:

Spanish
dog
bowl
end
['Spanish', 'dog', 'bowl']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.