Problem with input of more than one integer with input

Asked

Viewed 174 times

0

I’m having trouble capturing the input of more than one integer into one input.

Ex:

numero = int(input('Digite o primeiro número aqui: '))
numero_1 = int(input('Digite o segundo número aqui: '))
numero_2 = int(input('Digite o terceiro número aqui: '))
lista_numeros = [numero, numero_1, numero_2]

I would like to turn these 3 input’s into one.

Ex:

numeros = int(input('Digite os números aqui: '))
lista_numeros = [numeros]

but this second execution makes an error of:

Valueerror: invalid literal for int() with base 10: '1 2 3 5'

I believe it may be because of the gaps between the numbers.

2 answers

2


Realize that you must make a checking before to ensure that it is a number that is coming through the entrance, this is done by the function isdigit().

See below the example:

numeros = [int(v) for v in input('Valores: ').split() if v.isdigit()]
print(numeros)

Entree:

1 32 3 55

Exit:

[1, 32, 3, 55]

The output is a list of integers that were returned separately by int(v) through the comprehensilist on, following the specified condition isdigit(s) that simply checks if the value is a digit.

See working on Repl.it.

  • Thank you very much. Just a doubt I had here, this 'v' that was defined is only any variable can be X , Y or Z for example ?

  • Yes, it is created in the scope of the list comprehension and you can give the variable the name you want. In a Portuguese notation: valor para valor em variaveInteravel

  • Okay, thank you so much for your help!!

0

What you can do is capture the input line, divide it into substrings in the spaces, and then parse the integers:

entrada = input('Digite os números aqui: ')
numeros = [int(i) for i in entrada.split(' ')]

Browser other questions tagged

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