Appending letters to a list in a while loop
<p>I am trying to append the first word of a sentence to an empty list. The current code is below:</p>

<pre><code>sentence = input("Enter sentence: ")

subject = []
print (subject)

x = 0
while True:
    letter = sentence[x]
    if letter != " ":
        print (letter)
        subject.append(letter)
        x = x + 1

print (subject)
</code></pre>

<p>It currently prints this:</p>

<pre><code>Enter sentence: Cherries are red fruit

[]
C
h
e
r
r
i
e
s
</code></pre>

<p>It seems to ignore my attempt to append the result to the empty list... Help, please! </p>

<p>You'd better use <code>for</code> loop, it's less error-prone:</p>

<pre><code>sentence = input('Enter sentence: ')

subject = []
print(subject)

for letter in sentence:
    if letter == ' ':
        break
    else:
        print(letter)
        subject.append(letter)

print(subject)
</code></pre>

<p>If you want to break a sentence into words, there's a <a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="nofollow"><code>str.split</code></a> method, which can help you in simple cases:</p>

<pre><code>words = sentence.split()
first_word = words[0] if words else None
print(first_word)
</code></pre>

python while-loop append