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.
– roger roger