Input without line break, is it possible?

Tim Chase python.list at tim.thechases.com
Wed Dec 4 10:55:43 EST 2013


On 2013-12-04 07:38, geezle86 at gmail.com wrote:
> for i in range(8):
>    n = input()
> 
> When we run it, consider the numbers below is the user input,
> 
> 1
> 2
> 3
> 4
> 5
> 6
> (and so forth)
> 
> my question, can i make it in just a single line like,
> 
> 1 2 3 4 5 6 (and so forth)

Not easily while processing the input one at a time.  You can,
however, read one line of input and then split it:

  s = input()
  bits = s.split()
  if len(bits) != 8:
    what_now("?")
  else:
    for bit in bits:
      do_something(bit)

You could make it a bit more robust with something like:

  answers = []
  while len(answers) < 8:
    s = input()
    answers.append(s.split())
  del answers[8:] # we only want 8, so throw away extras
  for answer in answers:
    do_something(answer)

which would at least ensure that you have 8 entries.

-tkc







More information about the Python-list mailing list