Python- Runtime error(NZEC) - python-3.x

Question-
https://www.codechef.com/problems/SINS
Compiler used-
https://www.codechef.com/ide
Input method-
Custom input of codechef compiler.
My attempt-
T=int(input())
def fnc(a,b):
if b!=0:
return fnc(b,a%b)
else:
return int(a*2)
while T>0:
X,Y=map(int,input().split())
if X==0:
print(Y)
elif Y==0:
print(X)
elif X==Y:
print(X*2)
else:
f=fnc(X,Y)
print(f)
T=T-1
Issue:
I am getting the following runtime error:
Traceback (most recent call last):
File "./prog.py", line 8, in <module>
EOFError: EOF when reading a line
The output is correct but still there is this runtime error.

That is because the input() is getting End Of File (I assume you are using Python 3). You need to trap the EOFError exception and break out of the loop when you get it. You asked what I meant by that comment, this is what I mean:
try:
X, Y = map(int, input().split())
except EOFError:
break

Related

How do I fix this EOF error on python 3 version

I am working on a very basic problem on Hackerrank.
Input format:
First line contains integer N.
Second line contains string S.
Output format:
First line should contain N x 2.
Second line should contain the same string S.
sample test case
5
helloworld
my code is as: (on PYTHON 3)
n=int(input())
s=input()
print(2*n)
print(s)
I am getting error:
Execution failed.
EOFError : EOF when reading a line
Stack Trace:
Traceback (most recent call last):
File "/tmp/143981299/user_code.py", line 1, in <module>
N = int(input())
EOFError: EOF when reading a line
I tried this method to take input many times and this is the first time I am having this error. Can anyone please explain why?
use a try/except block to handle the error
while True:
try:
n=int(input())
s=input()
print(2*n)
print(s)
except:
break

while tokenization I'm encountering this error

I am a newbie to programming and I tried to do some interesting stuffs and ended up here, while string tokenizing I encountered this error while I can't solve this atmost
code:
import re
def cw(text):
counts=dict()
text=text.lower()
words=re.split(r'[^\w]',text)
for i in words:
print(words)
if i !="":
if i not in words:
counts[i]=1
else:
counts[i]+=1
return counts
def input():
with open("input.txt",'r') as f:
text=f.read()
counts=cw(text)
sort=sorted(counts.items(),key=lambda pair: pair[1],reverse=True)
print(sort)
if __name__ == "__main__":
input()
Error is:
Traceback (most recent call last):
File "C:/Users/surya/AppData/Local/Programs/Python/Python37-32/okay.py", line 35, in <module>
input()
File "C:/Users/surya/AppData/Local/Programs/Python/Python37-32/okay.py", line 27, in input
counts=cw(text)
File "C:/Users/surya/AppData/Local/Programs/Python/Python37-32/okay.py", line 17, in cw
counts[i]+=1
KeyError: 'as'

Learn Python the Hard Way -- ex17.py under python-3 environment

I try to learn this book under python-3 environment but it pops out an error when I try to run it. Is there anywhere to fix this?
Once I deleted
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
The code ran perfectly. So I think it should be the syntax problem between python 2 and python 3
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print("Copying from %s to %s" % (from_file,to_file))
# we could do these two on one line too, how?
in_file = open(from_file)
indata = in_file.read()
print("The input file is %d bytes long" % len(indata))
print("Does the output file exist? %r" % exists(to_file))
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
out_file = open(to_file, 'w')
out_file.write(indata)
print("Alright, all done")
out_file.close()
in_file.close()
When I try to run it, it should stops at input() and wait me hit the return key to continue. But in reality, the code stopped and an error called
"Traceback (most recent call last):
File "ex17.2.py", line 18, in <module> g
input("")
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
popped out.
Yes you are correct!! The error you are getting is due to python version change. This code works perfectly fine in python 3.x but fails in python version under 3.x.
Hope this helps.

EOFError in pickle.load and file not found error

elif(ch==2):
fh=open("emp1.txt","rb+")
fo=open("temp.txt","wb+")
ecode=input("Enter the Ecode :")
rec=(" ")
try:
while True:
emp1= pickle.load(fh)
if (emp1.ecode!=ecode):
pickle.dump(emp1,fh)
except(EOFError):
fh.close()
fo.close()
os.remove("empl.txt")
os.rename("temp.txt","emp1.txt")
print("")
running the following code gives me this error:
Traceback (most recent call last): File
"C:\Users\hello\Desktop\bhavi\python programming\Employ.py", line 78,
in
emp1= pickle.load(fh) EOFError
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"C:\Users\hello\Desktop\bhavi\python programming\Employ.py", line 85,
in
os.remove("empl.txt") FileNotFoundError: [WinError 2] The system cannot find the file specified: 'empl.txt'
What should i do now??
You should fix your path. In the first case, you write "emp1.txt"; and in the second, you write "empl.txt". If you look carefully, you should notice that there is a difference in those two strings.
Hint: '1' != 'l'
Your code could probably be refactored as well. While it is not possible for others to test your code since it is very incomplete, the following should work in its place. You will still need to verify it works.
elif ch == 2:
with open('emp1.txt', 'rb+') as fh, open('temp.txt', 'wb+') as fo:
ecode = input('Enter the Ecode: ')
while True:
try:
item = pickle.load(fh)
except EOFError:
break
else:
if item.ecode != ecode:
pickle.dump(item, fo)
os.remove(fh.name)
os.rename(fo.name, fh.name)
print()
I would use shelve, its much easier to use and it doesn't come up with to many errors in my experience. shelve is built on pickle but it just simplify it.
here is a short tutorial
http://python.wikia.com/wiki/Shelve

New line on error message in KeyError - Python 3.3

I am using Python 3.3 through the IDLE. While running a code that looks like:
raise KeyError('This is a \n Line break')
it outputs:
Traceback (most recent call last):
File "test.py", line 4, in <module>
raise KeyError('This is a \n Line break')
KeyError: 'This is a \n Line break'
I would like it to output the message with the line break like this:
This is a
Line Break
I have tried to convert it to a string before or using os.linesep but nothing seems to work. Is there any way I can force the message to be correctly shown on the IDLE?
If I raise an Exception (instead of KeyError) then the output is what I want, but I would like to still raise a KeyError if possible.
You problem has nothing to do with IDLE. The behavior you see is all from Python. Running current repository CPython interactively, from a command line, we see the behavior you reported.
Python 3.7.0a2+ (heads/pr_3947:01eae2f721, Oct 22 2017, 14:06:43)
[MSC v.1900 32 bit (Intel)] on win32
>>> raise KeyError('This is a \n Line break')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'This is a \n Line break'
>>> s = 'This is a \n Line break'
>>> s
'This is a \n Line break'
>>> print(s)
This is a
Line break
>>> raise Exception('This is a \n Line break')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: This is a
Line break
>>> raise IndexError(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: This is a
Line break
>>> try:
... raise KeyError('This is a \n Line break')
... except KeyError as e:
... print(e)
'This is a \n Line break'
>>> try:
... raise KeyError('This is a \n Line break')
... except KeyError as e:
... print(e.args[0])
This is a
Line break
I don't know why KeyError acts differently from even IndexError, but printing e.args[0] should work for all exceptions.
EDIT
The reason for the difference is given in this old tracker issue, which quotes a comment in the KeyError source code:
/* If args is a tuple of exactly one item, apply repr to args[0].
This is done so that e.g. the exception raised by {}[''] prints
KeyError: ''
rather than the confusing
KeyError
alone. The downside is that if KeyError is raised with an
explanatory
string, that string will be displayed in quotes. Too bad.
If args is anything else, use the default BaseException__str__().
*/
This section appears in the KeyError_str object definition in Objects/exceptions.c of the Python source code.
I will mention your issue as another manifestation of this difference.
There is a way to get the behavior you want: Simply subclass str and override __repr__:
class KeyErrorMessage(str):
def __repr__(self): return str(self)
msg = KeyErrorMessage('Newline\nin\nkey\nerror')
raise KeyError(msg)
Prints:
Traceback (most recent call last):
...
File "", line 5, in
raise KeyError(msg)
KeyError: Newline
in
key
error

Resources