Show Python words with 04 letters only

Asked

Viewed 130 times

-1

I’m learning Python and I’m doing an exercise, which is this one: Implement a program that asks the user for a list of words (i.e., strings) and then display on the screen, one per line, all 4-letter strings in this Python list

But I’m stuck and I couldn’t get more than one word out. If you can help me clarify, I’d appreciate it. The code I made is below.

nome = []
print('Olá')
nome.append(input('Digite um nome: '))

for n in nome:
    if len(n) == 4:
        print(n)
  • Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativities worth reading the Stack Overflow Survival Guide in English.

2 answers

1


Your code to validate the words with 4 letters and display them is correct, the problem is that you are running only once the code, ie stores 1 name, displays (or not) and successfully finishes the program.

If you want it to keep asking and printing the names have to put a loop. For example, the while, as long as the condition is true the process continues.

I tried to understand your problem and made some changes: I created a list to store all the names, put the while to continue asking for new names while not receiving an empty input and put the print at the end, after escaping from the loop.

Ahh, and in the list only names with exact 4 characters are added.

ListaNome = []
nome = input('Digite um nome: ')

while nome != '':
    if len(nome) == 4:
        ListaNome.append(nome)
    nome = input('Digite um nome: ')
    
for x in range(len(ListaNome)):
    print(ListaNome[x])
  • 1

    Thanks! I even thought and tried to apply the while, but I didn’t get it right. I still have a lot to learn. Once again I thank you!

  • @dougst search for the channel video course on Youtube, of Professor Guanabara. It has a python course from the beginning which is excellent

1

The creation of the empty list 'name' is not necessary, with the append, vc was adding only 1 string in the list, regardless of how many words were inserted into the input, so in IF the Len(name) would always be 1, not triggering the code within the IF.

Following example:

print('Olá')
nome = input("Digite um nome ").split(' ')
for n in nome:
    if len(nome) == 4:
        print(n)

. . . . . . .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.