Would you like to make a code that spells out the word?

Asked

Viewed 168 times

1

I’m new to programming and I’m trying to put together a script where I type in a word and he spells it out for me!

I’ve assembled the following code!

nome = input('palavra para soletrar:')

while True :
    print('a primeira letra é',nome[0],'!')
    print('a segunda letra é',nome[1],'!')
    print('a terceira letra é',nome[2],'!')
    print('a quarta letra é',nome[3],'!')
    print('a quinta letra é',nome[4],'!')
    nome = input('palavra para soletrar:')

Only when the word is smaller, the code stops! I’m trying to build a bigger one and when I put a word with less than 4 letters it spells it the same way and repeat the code!

  • Do not set the amount of letters, vary according to the amount of letters of the given word.

  • If the answer solved your problem, you can aceitá-la, by clicking on V next to the answer. See here why accept. Although not mandatory, this practice is encouraged on the site, indicating to future visitors that such a response solved the problem. And when you get 15 points, you can also vote in any useful responses.

2 answers

0


For you to spell a word you can implement the following algorithm:

  1. Captures a word;
  2. Implements a loop loop loop;
  3. In each loop interaction displays the position and the referred letter;
  4. Ask if you wish to continue.

With this logic I implemented the following code:

while True:
    nome = input('Palavra para soletrar: ')

    cont = 0
    for letra in nome:
        cont += 1
        print(f'A {cont}ª letra é: {letra}')
    print()
    resp = input('Dsejas continuar? [S/N] ').upper()
    while (len(resp) != 1) or (resp not in 'SN'):
        print('Valor INVÁLIDO?')
        resp = input('Dsejas continuar? [S/N] ').upper()
    if resp == 'N':
        break

Note that when we execute the code we receive the following message: Digite uma palavra: . At this point we must enter a word. Then the loop of repetition for will traverse the string palavra and will display the position and the letter. Then ask us if we want to continue. And if we type the letter S, the code will be re-examined. If we type the letter N, the code will be closed.

0

If you want to iterate through the characters of a string and at the same time get the position of each one, just use enumerate. In a nutshell, I would:

palavra = input('palavra para soletrar:')
for i, letra in enumerate(palavra, start=1):
    print(f'A {i}ª letra é {letra}')

Thus, with each iteration, letra will be one of the characters in the string and i will be their position. Only by default, enumerate starts counting indexes at zero, but I can indicate a different initial value by passing the argument start.


And in your case you’re making one loop to ask for several words, and can improve a little. For example, do not need to put a input before the while and another within it. If you need for example to change the message of input or something like that, you’ll have to change in 2 places. So do it all just once, inside the loop.

And how is a loop infinite, it would be interesting to have some stop condition. For example, if the typed word is empty (the user only type one ENTER), you could terminate the while:

while True:
    palavra = input('palavra para soletrar:')
    if not palavra: # se não foi digitado nada
        break # sai do while
    print(f'soletrando "{palavra}"')
    for i, letra in enumerate(palavra, start=1):
        print(f'A {i}ª letra é {letra}')

Of course you can use any logic you want to interrupt the program (like the example in another answer). But the main point is that you don’t need to repeat the input outside and inside the loop.


And if you want the output to have the ordinal numbers spelled out, an alternative is to install the module num2words:

from num2words import num2words

while True:
    palavra = input('palavra para soletrar:')
    if not palavra:
        break
    print(f'soletrando "{palavra}"')
    for i, letra in enumerate(palavra, start=1):
        print(f'O {num2words(i, to="ordinal", lang="pt_BR")} caractere é {letra}')

The problem is that the num2words does not have option for the ordinal numbers in the feminine (it only returns "first" and there is no option to return "first"). So the way is to do the gambit:

def ordinal_fem(i):
    s = num2words(i, to="ordinal", lang="pt_BR")
    return s[:-1] + 'a' # troca a última letra por "a"

There in the loop just use the above function:

for i, letra in enumerate(palavra, start=1):
    print(f'A {ordinal_fem(i)} letra é {letra}')

Or you can search for other libs that treat these cases (in a quick search, I found this, but I didn’t get to test).

It is also worth remembering that input accepts anything that is typed by the user, and may even be a multi-word phrase, or only spaces or things that are not necessarily words (such as 123, !@#$%, etc). Of course, it is already outside the scope of the question, but if you want additional material on the subject, you can take a look here, here and here.

Browser other questions tagged

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