I am trying to get multiple names separated by newlines from the console and put them into a variable. Let's assume I want to get input from the terminal forever (I'll add some code to break out of the loop later). I know how to do it with a while loop and recursion, but I would like to be able to do it with a for loop.
In the below example when I get "peter" as input from the terminal I get each letter rather than a whole line at a time:
for name in input():
print(name)
Now, if I use sys.stdin the name variable becomes "peter\n":
for name in sys.stdin:
print(name)
Is there a easy way to get input() to give "name" a whole line rather than individual characters? Or just by the nature of using for in I am going to be iterating through the characters in the input? Are there any inherent risks/problems with getting input in this fashion? Is there a "standard" way of getting input in a situation like this?
I am using Python 3.5.1 on Ubuntu 15.10.
input()returns a string which is an iterable, so therefore when you try and iterate over it you are getting each character one by one.sys.stdinisn't a function, it actually is a file object which is used by the system to get the standard input, thereforefor name in sys.stdinbehaves like it would do on a file: reading it line by line.