Integer variable that controls the loop

Asked

Viewed 80 times

3

I’m asking the fifth question of this exercise:

Question 5: Given a list of ints, Return True if first and last number of a list is same

The code is down. In it, while the user type an integer other than "-1", the value is added to the list and then the first value of the list is compared, lista[0], with the last value of the list, lista[-1].

The code doesn’t work exactly as it should because the way I know how to do it is to use a variable to control the loop. Unfortunately, as the variable num only accepts whole, ended up using "-1". I need a variable control the loop, so the user can feed the list as long as he wants.

However, as negative numbers are also integers, if the user wants to add the "-1" in the list to compare, the block ends up being terminated without the result. I’m looking for a solution.

def verificaNumeros(num):
    num = 0
    lista = []

    while (num != -1):
        num = int(input('Digite os números: '))
        lista.append(num)
        if -1 in lista:        
            lista.remove(-1)#remove o -1, pois ele é uma variável que controla o loop, e não o valor que o usuaŕio quer inserir na lista.        
            if(lista[0]==lista[-1]):
                 return True
            else: 
                 return False

1 answer

2


If any number can be accepted, then you should not use a number as a condition to exit the loop.

An alternative would be to take advantage of the fact that the function input returns a string (assuming you are using Python 3), then you set a specific value (for example, the letter "s") to indicate that you should exit the loop.

If the user does not type "s", then you use int to convert what was typed to a number. If it is not a number, you can capture the ValueError and display a message. The code looks like this:

numeros = [] # lista com os números
while True:
    s = input('Digite um número (ou "s" para sair): ')
    if s == 's':
        break # sai do loop
    try:
        # tenta converter para número e adicionar na lista
        numeros.append(int(s))
    except ValueError: # não foi digitado um número
        print('Você não digitou um número válido')

if len(numeros) < 2:
    print('Precisa de pelo menos dois números')
else:
    iguais = numeros[0] == numeros[-1]
    print('O primeiro e último número são {}'.format('iguais' if iguais else 'diferentes'))

That is, if the user enters a number, it is added to the list. If you type "s", exit the loop and check whether the first and last are equal.
If you type anything else (some other letter, for example), the conversion to number fails (the function int spear one ValueError and he falls into the block except) and a message is displayed indicating what happened - but it does not leave the loop, so it asks to be typed another number.

Notice that I use len (which returns the list size) to check if the list has at least two numbers (because it seems to me that it makes no sense to compare the first with the last if it has only one element, and even less if it is empty).
For the case of having an element, we can even assume that the first and last are equal, because they are exactly the same element, it is up to you to consider this case or not.

If there are at least two numbers, I compare and display the respective message. Note that I saved the result of the comparison in the variable iguais, and I use the value of it to show the message according to the result. If you got too confused, you can also exchange the end for:

if len(numeros) < 2:
    print('Precisa de pelo menos dois números')
else:
    if numeros[0] == numeros[-1]:
        print('O primeiro e último número são iguais')
    else:
        print('O primeiro e último número são diferentes')

Another option is to simply read the numbers until you type something other than a number:

while True:
    try:
        numeros.append(int(input('Digite um número (ou qualquer coisa que não seja número para encerrar a leitura): ')))
    except ValueError:
        break

... compara o primeiro e último

Thus, while the user type numbers, they are added in the list. When you enter anything other than number, it exits the loop and follows with the comparison between the first and the last.


How you want to create a function that returns True or False, would look like this:

def verifica_numeros():
    numeros = []
    while True:
        try:
            numeros.append(int(input('Digite um número: ')))
        except ValueError:
            break

    if len(numeros) < 2:
        print('Precisa de pelo menos dois números')
        return False
    else:
        return numeros[0] == numeros[-1]

Note that I can directly return the result of the comparison numeros[0] == numeros[-1], because it will always result in True or False.

  • The second code you posted meets the needs(keep reading the numbers until you type something other than a number). Thank you.

Browser other questions tagged

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