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
Related
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
I have the following code:
test_file = open("test.txt","r")
line1 = test_file.readline(1)
test_file.close()
line1 = int(line1)
print(line1)
I have 12 written into the file.
I simply get the output 1.
Can someone please explain what is wrong with this code?
The function readline() has no parameter for reading a special line. It reads from the file line-by-line for each call. To read just the first line call the function one time like:
line1 = test_file.readline()
You have passed the size to read in your code. It read the bytes accordingly to passed size in readline method
Also use with to open file (in pythonic way)
with open("test.txt","r") as test_file:
line1 = test_file.readline()
line1 = int(line1)
print(line1)
When you specify 1, you are telling readline() to take only the first character in your line, it's better to do this update on your code:
test_file = open("test.txt","r")
line1 = test_file.readline() # Remove the indice 1
test_file.close()
line1 = int(line1)
print(line1)
Or in one line like this:
print(int(open("test.txt","r").readline()))
i dont under stand how to make this loop
term = input("")
file = open('file.txt')
for line in file:
line.strip().split('/n')
if term in line:
print(line)
if term in line:
print('Not on database, (try using caps)')
file.close()
(i know it is incorrect)
If by "repeat" you mean you want the user to be able to input a term multiple times, then just use a while loop.
while True:
term = input("")
file = open('file.txt')
for line in file:
line.strip().split('/n')
if term in line:
print(line)
if term in line:
print('Not on database, (try using caps)')
file.close()
I am not sure how many times you want to be able to loop, but this loop will go indefinitely.
I guess what you need is this.
term = input("")
# file is a python object by default, so it's better not to use it.
f = open('file.txt')
# Put each line in the file into a list
content = f.readlines()
for line in content:
# str.strip() does not replace the original string
# I modify it so that it is replaced.
line = line.strip()
if term in line:
print(line)
# The line below is unnecessary because it's the same condition as the previous if statement
# if term in line:
print('Not on database, (try using caps)')
f.close()
You can open the file using with and loop through the lines.
term = input("")
with open('file.text') as f:
for line in f.readlines():
if term in line.strip():
print(line)
break #breaks for loop and exits
As part of an assignment I'm writing an assembler in python that takes simplified assembly language and outputs binary machine language. Part of my code is below, where I'm reading from the assembly code in two passes. The first pass (the first line of with open(filename, "r") as asm_file) in the first block of reading from the file asm_file doesn't seem to be executing. The second one is executing fine, well it's not outputting the correct binary because the first block doesn't seem to be running correctly or at all. Am I using the "with open(filename. "r") as file:" correctly? What am I missing? Thanks in advance.
For completeness an input file is given below the code:
if __name__ == "__main__":
#fill Symbol Table and C instruction Tables
symbol_table = symbolTable()
symbol_table.initialiseTable()
comp_table = compTable()
comp_table.fillTable()
dest_table = destTable()
dest_table.fillTable()
jump_table = jumpTable()
jump_table.fillTable()
#import the file given in the command line
filename = sys.argv[-1]
#open output_file
output_file = open('output.hack', 'w')
#open said file and work on contents line by line
with open(filename, "r") as asm_file: ##### This one doesn't seem to run because
#1st pass of input file ##### The print command below doesn't output anything
num_instructions = -1
for line in asm_file:
#ignoring whitespace and comments
if line != '\n' and not line.startswith('//'):
num_instructions += 1
#remove in-line comments
if '//' in line:
marker, line = '//', line
line = line[:line.index(marker)].strip()
#search for beginning of pseudocommand
if line.startswith('('):
num_instructions -= 1
label = line.strip('()')
address = num_instructions + 1
symbol_table.addLabelAddresses(label, address)
print(num_instructions) ###### This print command doesn't output anything
with open(filename, "r") as asm_file:
#2nd pass of input file
for line in asm_file:
#ignoring whitespace and comments
if line != '\n' and not line.startswith('//') and not line.startswith('('):
#remove in-line comments
if '//' in line:
marker, line = '//', line
line = line[:line.index(marker)].strip()
#send each line to parse function to unpack into its underlying fields
instruction = parseLine(line.strip(' \n'))
inst = Instruction(instruction)
binary_string = inst.convertToBin()
#write to output file
output_file.write(binary_string +'\n')
output_file.close()
An input file example:
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/06/max/Max.asm
// Computes R2 = max(R0, R1) (R0,R1,R2 refer to RAM[0],RAM[1],RAM[2])
#R0
D=M // D = first number
#R1
D=D-M // D = first number - second number
#OUTPUT_FIRST
D;JGT // if D>0 (first is greater) goto output_first
#R1
D=M // D = second number
#OUTPUT_D
0;JMP // goto output_d
(OUTPUT_FIRST)
#R0
D=M // D = first number
(OUTPUT_D)
#R2
M=D // M[2] = D (greatest number)
(INFINITE_LOOP)
#INFINITE_LOOP
0;JMP // infinite loop
Your problem seems to be that your code checks if a line starts with a (, but in the assembly it has a tab before an instruction so that it doesn't work. You should probably do a line.strip() after your first if statement like so
with open(filename, "r") as asm_file:
num_of_instructions = -1
for line in asm_file
if line != "\n":
line.strip()
#rest of code
Incidentally, is the print statement supposed to execute every time it finds a line? Because if it doesn't, you should put it after the for loop. That is why it is not outputting anything
Edit: As #TimPeters says, the print statement will also only execute if it starts with an open bracket and has a comment in it
In the first with, starting with
#search for beginning of pseudocommand
are you quite sure you don't want that and the following lines dedented a level?
As is, the only way to get to your print is if a line satisfies both
if '//' in line:
and
if line.startswith('('):
There are no lines in your input file satisfying both, so the print never executes.
In the second with, there are only two indented lines after its
if '//' in line:
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