How to input() stop after space instead of line break in Python3

Asked

Viewed 783 times

0

I’m looking to capture several numbers on this graduate:

2 4 5 3 5 0 4 

As a number of numbers undefined and without using an auxiliary list, I want to use only one variable

for _ in range(0,n):
    num = int(input())

I know only by creating a list

for _ in range(0,q):
    lista +=[int(input().split(' '))]
  • But if the numbers are in the format 2 4 5 3 5 0 4 then num = int(input()) will never work. Itself split which has in question already returns a list. What exactly is the doubt ?

3 answers

2

Really the question is confusing but if the list is "infinite", just read an entire line and then separate the elements:

#!/usr/bin/python3

# recebe cada número de uma só vez.
print('Digite a lista de números separada por espaços, <Enter> finaliza')
entrada = input('=> ')

# separa a string por espaços e converte em uma lista de inteiros.
lista = [ int(i) for i in entrada.split(' ') ]

# imprime a lista, apenas para referência.
print(lista)
  • if you have a space at the beginning of the input, as it is in the question, this break code - has to put a filter "`...if i`` in the list-comprehension.

0

From what I understand, you wish capturar all the valores typed in a single line. That is, you would like to implement a program that solicitar the typing of the values, the user was able to digita-los in a single line.

According to my understanding the algorithm would be...

valores = list(map(int, input('Digite os valores: ').split()))
print(f'\033[32mValores digitados: {valores}\033[m')

Note the functioning of the algorithm in repl it..

Note that to correctly utilize this algorithm, you have to:

  1. Run the algorithm;
  2. Type todos the values in the mesma line separados by a espaço;
  3. Put pressure on Enter.

Also note that this algorithm is capable of capturing a number indefinido of values.

0

It’s an extremely confusing question and by the little I understand you want to find a value " " the system stops, if it is not correct the question. Anyway it follows the solution to what I said:

import sys

lista = int(input("Digite a lista"))
newLista = lista.split(' ')

for i in newLista:
    if(i == " "): #Identifica o " "
        sys.exit() #O sistema irá parar

If you want to separate each term from the list, you have to use another .split() and another marker. Input data shall contain such a marker.

Browser other questions tagged

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