Unexpected outputs of a user’s serial listing code

Asked

Viewed 60 times

1

The code I asked that asks the user the series it accompanies and has some problems:

first problem: the line counter serie = str (input("Digite a sua {}a série favorita: ".format(i+1))) does not update to 2a, 3a, 4a and always stays that way:

1st loop:

Digite a sua 1a série favorita:

2nd loop

Digite a sua 1a série favorita:

...

second problem: I would like to add a condition below the if serie != '': that shows a message that the user cannot enter a single character of the series but I don’t know how to do it.

third problem: There is a for at the end of the code that lists all the series that the user typed**, but it’s not the way I wanted it to be.

The way I wanted

1a serie favorita: The Punisher

2a serie favorita: O Mundo Sombrio de Sabrina

...

The way you find yourself

: ['', 'The Punisher', 'O Mundo Sombrio de Sabrina', ...]

The Punisher: ['', 'The Punisher', 'O Mundo Sombrio de Sabrina', ...]

O Mundo Sombrio de Sabrina: ['', 'The Punisher', 'O Mundo Sombrio de Sabrina', ...]

...

The code I made:

nome = ""
series = ['']
i = 0
while nome == "":
    nome = str (input("Digite seu nome: "))

print ("{} quero lembrar que não é permitido digitar apenas uma letra".format(nome))
print ("Deseja responder a pergunta? ")
resposta = str (input("S - Sim | N - Não: "))[0]

while resposta == 'S' or resposta == 's':
    serie = str (input("Digite a sua {}a série favorita: ".format(i+1)))

    if serie != '':
        print ("Nome da série: {}".format(serie))

    series.append(serie)

    print ("Deseja digitar mais alguma série {}?".format(nome))
    resposta = str (input("S - Sim | N - Não: "))[0]

if resposta == 'N' or resposta == 'n':
    print ("{} Bye!".format(nome))

for i in series:
    print ("{}: {}".format(i,series))

2 answers

2


The first problem (does not update the serial number) happens because you are not incrementing the counter i inside the loop.

The second problem is solved by checking the size of the typed string, through the function len.

The third problem (show series) happens because of this loop:

for i in series:
    print("{}: {}".format(i, series))

The variable series is a list containing all series. When doing for i in series, every iteration of loop, the variable i contains the name of one of the series. But you print the name (the variable i) and the whole list (the variable series), so the way out is the way you indicated.

Other details for tidying up:

  • the variable series starts as a list containing an empty string (series = ['']). But there is no reason for it, just assign the value [] to start the list empty
  • the function input already returns a string, it is not necessary to use str(input(...))
  • if you want to iterate through the list elements along with their index, just use enumerate

The code goes like this:

nome = ''
while not nome:
    nome = input("Digite seu nome: ").strip()

print("{}, quero lembrar que não é permitido digitar apenas uma letra".format(nome))
print("Deseja responder a pergunta? ")
resposta = input("S - Sim | N - Não: ").strip()[0]

i = 1
series = []
while resposta.lower() == 's':
    while True:
        serie = input("Digite a sua {}a série favorita: ".format(i)).strip()
        if len(serie) <= 1:
            print('Nome deve ter mais de uma letra')
        else:
            break # nome OK, sai do while True

    # o while True acima já garante que o nome estará preenchido
    print("Nome da série: {}".format(serie))
    series.append(serie)
    i += 1

    print("Deseja digitar mais alguma série, {}?".format(nome))
    resposta = input("S - Sim | N - Não: ").strip()[0]

if resposta.lower() == 'n':
    print("{}, Bye!".format(nome))

for i, serie in enumerate(series):
    print("{}: {}".format(i + 1, serie))

Other details:

  • used strip() to remove the start and end spaces of the strings returned by input (is not strictly necessary, use if you want)
  • the loop while True already ensures that the series name must be filled in, so I don’t need to test the name before printing it
  • to check the option, I use resposta.lower() == 's' - for lower() turns the string into lowercase. But if you want, you can also do while resposta in ('S', 's'):.
  • while not nome is the same that while nome == ""

You can also break each part of the code into functions (one to read the series name, another to the options, etc), so the code gets a little more organized:

def ler_opcao(mensagem, nome=None):
    if nome:
        print('{}, {}? '.format(mensagem, nome))
    else:
        print('{}? '.format(mensagem))
    # já retorna a opção como letra minúscula
    return input("S - Sim | N - Não: ").strip()[0].lower()


def ler_nome_serie(i):
    while True:
        serie = input("Digite a sua {}a série favorita: ".format(i)).strip()
        if len(serie) <= 1:
            print('Nome deve ter mais de uma letra')
        else:
            return serie  # nome OK, retorna o nome da série


nome = ''
while not nome:
    nome = input("Digite seu nome: ").strip()

print("{}, quero lembrar que não é permitido digitar apenas uma letra".format(nome))
resposta = ler_opcao("Deseja responder a pergunta")

i = 1
series = []
while resposta == 's':
    serie = ler_nome_serie(i)
    print("Nome da série: {}".format(serie))
    series.append(serie)
    i += 1

    resposta = ler_opcao("Deseja digitar mais alguma série", nome)

if resposta == 'n':
    print("{}, Bye!".format(nome))

for i, serie in enumerate(series):
    print("{}: {}".format(i + 1, serie))

Another detail is the if resposta == 'n':. The while only checks if the option is s. So if you type, for example, x, he also comes out of while, but then it doesn’t enter the if (because it wasn’t typed n). If you want to always print the "Bye" message, simply remove the if.

  • 1

    Some things you explained will be of great help, thank you very much.

1

For the first problem you can do the following: i = i + 1 before placing inside the Format and then use the Format(i), because the way you’re doing it isn’t increasing the i, the code is only displaying the sum of i (which is 0) with 1.

The second problem can be solved with the function len(sua string) within the if (this function returns the amount of items in a set, which can be string, list, etc).

The third problem occurs because for every iteration vc displays the full series vector, the variable i of for (which should have another name, which was not used before) is an item of the vector, in your case the vector is like this [' ', 'The Punisher', 'O Mundo Sombrio de Sabrina'], and the for is displaying the current item and then all items with each iteration.

For you to solve, in the vector statement series Remove the quotes from inside the [], within the for use the i (by another name) in place of series and in place of the i use a counter also inside the for.

Browser other questions tagged

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