Home > Software engineering >  Why 'for' loop is holding onto the last letter of the string?
Why 'for' loop is holding onto the last letter of the string?

Time:09-02

I am getting the last letter of the randomly chosen word. Please look at the code and answer why

word_list = ["aardvark", "baboon", "camel"]
answer = random.choice(word_list)
for letters in answer:
  letters =letters
print(letters)

It will print either 'kk', 'nn', or 'll'. What is making this loop holding the last letter of the word? Thanks

CodePudding user response:

# working example
import random

word_list = ["aardvark", "baboon", "camel"]
answer = random.choice(word_list)
letters = ""

for letter in answer:
  letters =letter

print(letters)

It printed "kk" "nn" or "ll" because those are the last letters of each element of the list

aardvar(k)
baboo(n)
came(l)

and when you did

letters =letters

it kept the last letter and then printed it plus itself.

Additionally I'm not sure why you iterate over the word and recreate it, but I kept it in the answer to keep it similar to the code you have.

CodePudding user response:

This is because your letters variable is changing at each iteration:
At first, if the choice is "camel" it'll be:
letters -> c
letters -> cc (Because of your instruction)

Then second iteration, letters is changing:
letters -> a
letters -> aa
etc

Try this instead:

word_list = ["aardvark", "baboon", "camel"]
answer = random.choice(word_list)

result = ''     # We'll store the result here
for letters in answer:
  result  = letters
print(result)

CodePudding user response:

for letters in answer:
    letters =letters

Each time through the loop, letters takes on the value of the next letter in the word.

Then inside the loop, you add letters to itself. So on the first loop iteration you get aa.

But, because letters itself is the loop variable, it is reassigned a fresh value each time through the loop, discarding the previous contents.

It seems like you really wanted to do this:

word = ''
for letter in answer:
    word  = letter
  • Related