I try to output the sum of 1 - 12 lines which contain each two numbers which are seperated by ' '. Because I don't know how many lines will be inputed, I have an endless loop, which will be interupted if the line is empty. But if there is no input anymore, there won't be any empty input and the program is stuck in the input function.
while True:
line = input()
if line:
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
else:
break
So after the last outputed sum I want the program to stop. Maybe it is possible with a time limit?
It looks like the automated input is coming in via sys.stdin. In that case you can just read from the standard input stream directly. Try this:
def main():
import sys
lines = sys.stdin.read().splitlines()
for line in lines:
print(sum(map(int, line.split())))
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
With an input of "1 2\n3 4" to the sys.stdin stream, this script prints 3 and 7.
For the case without timeout, and the case allowing you to capture the content (which is usually handy).
The following code has been tested in HACKERRANK. I am sure HackerEarth is the same.
contents = []
while True:
try:
line = input()
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
except EOFError:
break
contents.append(line)
if you don't care about the input.
while True:
try:
line = input()
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
except EOFError:
break
Related
Imagine unlimited multiline input with some URL addresses, for example:
How would you get that addresses from the input separately?
Following was close, but actually not helping:
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
source: How to get multiline input from user
And other advices I consider completely useless: https://python.plainenglish.io/taking-multiple-inputs-from-user-in-python-3-6cbe02d03a95
If I understand the problem correctly, this may help:
lines = []
try:
while line := input():
lines.append(line)
except EOFError:
pass
print(lines)
This will handle both interactive and redirected input (stdin)
There is a function you could use:
import sys
sys.stdin.read()
But I'm not sure this is a great idea because it won't know when to stop reading. The traditional input() function will detect a \n symbol via the return key, then end input.
I think looping would be the best way forward.
Like:
urls = ''
while True:
url = input()
if url:
urls += url + '\n'
else:
break
Have a nice day.
I would like to have a user input in python, which is not only one line. Furthermore, I don't know how many lines there will be. Example:
line1 ...
line2 ...
line3 ...
I've already tried this:
lines = []
try:
while True:
line = input()
if line:
line = line.split(" ")
lines.append(line)
else:
break
except EOFError:
pass
The problem with this is, that when I have an empty line it doesn't work anymore.
The indicator that the user is done is the problem. I want a text to be pasted in as user input and after that it should stop.
Thanks for your replies!
You could try something like this:
lines = []
while True:
inp = input()
if inp:
lines.append(inp)
else:
break
You have multiple solutions to pass multiple lines as arguments to your Python program.
FIRST SOLUTION:
You can invoke a python program and process the standard input using the input method. This allows you to process any number of lines and the content is added while your program is running. However, the users must have a way to indicate that the input has finished (a line containing "EOF", an empty line, etc.) in order to allow the program to stop looking for more input and begin other processes.
$ cat prog3.py
def main():
# Retrieve input
lines = []
line = input("Enter first line or empty line to end\n")
lines.append(line)
while line:
line = input("Enter next line or empty line to end\n")
lines.append(line)
# Process input lines
for l in lines:
print(l)
# Process input lines
for l in lines:
print(l)
if __name__ == "__main__":
main()
$ python prog.py
Enter first line or empty line to end
line1 # Written by user
Enter next line or empty line to end
line2 # Written by user
Enter next line or empty line to end
line3 # Written by user
Enter next line or empty line to end
line1
line2
line3
SECOND SOLUTION:
You can dump all the lines to a file, pass the file as an argument to your python program and process each line of the file separately. Notice that this method also requires to know the number of lines and their content before invoking the python program.
$ cat prog2.py
def main():
import sys
file_name = str(sys.argv[1])
with open(file_name, 'r') as f:
for l in f:
print(l)
if __name__ == "__main__":
main()
$ cat 1.in
line1
line2
line3
$ python prog.py "1.in"
line1
line2
line3
THRID SOLUTION:
If you want to use the regular python sys.argv you need to wrap all the lines as a string, adding a delimiter between lines, and pass them as a single parameter to your python program. Then, in the python program, you need to parse the string into multiple lines and proceed one by one.
This feels a little cheating for me but it might come useful in some use cases.
Notice that this method requires you to know the number of lines and their content before invoking the python program.
$ cat prog1.py
def main():
import sys
lines = sys.argv[1].split("|")
for l in lines:
print(l)
if __name__ == "__main__":
main()
$ python prog.py "line1|line2|line3"
line1
line2
line3
This question already has answers here:
How to read multiple lines of raw input?
(16 answers)
Closed 6 years ago.
I want to write a program that gets multiple line input and work with it line by line. Why isn't there any function like raw_input in Python 3?
input does not allow the user to put lines separated by newline (Enter). It prints back only the first line.
Can it be stored in a variable or even read it to a list?
raw_input can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:
Python 3
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
Python 2
print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
try:
line = raw_input("")
except EOFError:
break
contents.append(line)
In Python 3.x the raw_input() of Python 2.x has been replaced by input() function. However in both the cases you cannot input multi-line strings, for that purpose you would need to get input from the user line by line and then .join() them using \n, or you can also take various lines and concatenate them using + operator separated by \n
To get multi-line input from the user you can go like:
no_of_lines = 5
lines = ""
for i in xrange(no_of_lines):
lines+=input()+"\n"
print(lines)
Or
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
input(prompt) is basically equivalent to
def input(prompt):
print(prompt, end='', file=sys.stderr, flush=True)
return sys.stdin.readline()
You can read directly from sys.stdin if you like.
lines = sys.stdin.readlines()
lines = [line for line in sys.stdin]
five_lines = list(itertools.islice(sys.stdin, 5))
The first two require that the input end somehow, either by reaching the end of a file or by the user typing Control-D (or Control-Z in Windows) to signal the end. The last one will return after five lines have been read, whether from a file or from the terminal/keyboard.
Use the input() built-in function to get a input line from the user.
You can read the help here.
You can use the following code to get several line at once (finishing by an empty one):
while input() != '':
do_thing
no_of_lines = 5
lines = ""
for i in xrange(5):
lines+=input()+"\n"
a=raw_input("if u want to continue (Y/n)")
""
if(a=='y'):
continue
else:
break
print lines
My current code reads user input until line-break.
But I am trying to change that to a format, where the user can write input until strg+d to end his input.
I currently do it like this:
input = raw_input ("Input: ")
But how can I change that to an EOF-Ready version?
In Python 3 you can iterate over the lines of standard input, the loop will stop when EOF is reached:
from sys import stdin
for line in stdin:
print(line, end='')
line includes the trailing \n character
Run this example online: https://ideone.com/rUXCIe
This might be what most people are looking for, however if you want to just read the whole input until EOF into a single variable (like OP), then you might want to look at this other answer.
Use file.read:
input_str = sys.stdin.read()
According to the documentation:
file.read([size])
Read at most size bytes from the file (less if the read hits EOF
before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached.
>>> import sys
>>> isinstance(sys.stdin, file)
True
BTW, dont' use input as a variable name. It shadows builtin function input.
You could also do the following:
acc = []
out = ''
while True:
try:
acc.append(raw_input('> ')) # Or whatever prompt you prefer to use.
except EOFError:
out = '\n'.join(acc)
break
With sys.stdin.readline() you could write like this:
import sys
while True:
input_ = sys.stdin.readline()
if input_ == '':
break
print type(input_)
sys.stdout.write(input_)
Remember, whatever your input is, it is a string.
For raw_input or input version, write like this:
while True:
try:
input_ = input("Enter:\t")
#or
_input = raw_input("Enter:\t")
except EOFError:
break
print type(input_)
print type(_input)
print input_
print _input
Instructions:
Write a program that writes a series of random numbers to a file.
Each random number should be in the range of 1 through 100.
The application should let the user specify how many random numbers the file will hold.
Here's what I have:
import random
afile = open("Random.txt", "w" )
for line in afile:
for i in range(input('How many random numbers?: ')):
line = random.randint(1, 100)
afile.write(line)
print(line)
afile.close()
print("\nReading the file now." )
afile = open("Random.txt", "r")
print(afile.read())
afile.close()
A few problems:
It's not writing the random numbers in the file based on the range the user is setting.
The file can't close once opened.
When the file is read, nothing.
While I thought the set up was okay, it seem to always get stuck on execution.
Get rid of for line in afile:, and take out what was in it. Also, because input returns a string in Python 3, convert it to an int first. And you are trying to write an integer to a file, when you have to write a string.
This is what it should look like:
afile = open("Random.txt", "w" )
for i in range(int(input('How many random numbers?: '))):
line = str(random.randint(1, 100))
afile.write(line)
print(line)
afile.close()
If you are worried that the user might input a non-integer, you can use a try/except block.
afile = open("Random.txt", "w" )
try:
for i in range(int(input('How many random numbers?: '))):
line = str(random.randint(1, 100))
afile.write(line)
print(line)
except ValueError:
# error handling
afile.close()
What you were trying to do was iterate through the lines of afile, when there were none, so it didn't actually do anything.
import random
ff=open("file.txt","w+")
for _ in range(100):
ff.write(str(random.randrange(500,2000)))
ff.write("\n")
ff.seek(0,0)``
while True:
aa=ff.readline()
if not aa:
print("End")
break
else:
if int(aa)%2==0:
print(int(aa))
ff.close()