while loop until empty string in online interpreter - python

Why does my program work in PyCharm but in online interpreter gives this error:
Traceback (most recent call last): File "Solution.py", line 4, in
s = input() EOFError: EOF when reading a line
Here's the part of code that matters:
i = 0
while True:
s = input()
if s == '':
break
else:
...
I'm trying to input strings until empty string occurs but it always gets stuck on line with empty string.
Thanks in advance and sorry if I'm sloppy with my question (my 1st question).

Perhaps you can handle there exception with try and except:
while True:
try:
s = input()
...
except EOFError:
break
...

Related

EOFError: EOF when reading a line, is there another way for me to write this code to prevent this?

import math
r=input("Please enter the radius")
h=input("Please enter the height")
def cone_area(r,h):
while True:
try:
r,h = float(r),float(h)
break
except ValueError:
return 'Error not a number'
a=((math.pi*r*(r+math.sqrt(r*r+h*h)))) # surface area formula
return round(a,4)
print(cone_area(r,h))
Here is the full error message:
Please enter the radius ↩
Error ↩
Traceback (most recent call last):
File "__tester__.python3", line 3, in <module>
r=input("Please enter the radius") #asks user for radius and height
EOFError: EOF when reading a line
For clarification, it works fine using python idle but I have to submit this for work into an online python interpreter which is where I get the error message. Another user also confirmed they could replicate this on linux. Where did I go wrong in my code?
Use try except to solve this problem
try:
print(input())
except EOFError:
exit()
Extra:
the while True: can be removed to increase efficient a bit.
Full code:
import math
def cone_area(r,h):
try:
r,h = float(r),float(h)
except ValueError:
return 'Error not a number'
a=((math.pi*r*(r+math.sqrt(r*r+h*h)))) # surface area formula
return round(a,4)
try:
while True: #infinity amount of input until EOF
r=input("Please enter the radius")
h=input("Please enter the height")
print(cone_area(r,h))
except EOFError:
print("input finish")

How to manage input errors from user in Python?

I am trying to write a program which accepts multiple inputs from user and do whatever is required but i don't want the program execution stop when user gives some error in the input rather i would like that line of program to be repeated again and again until the user gives a valid input or cancel the operation.
For example i have the following piece of program :-
# Error handling
i=int(eval(input("Enter an integer: " )))
print(i)
Now if the user enters a string following error is occurs :
Enter an integer: helllo
Traceback (most recent call last):
File "C:/Users/Gaurav's PC/Python/Error Management.py", line 2, in <module>
i=int(input("Enter an integer: " ))
ValueError: invalid literal for int() with base 10: 'helllo'
HERE, I want Python to re-run the line 2 only for a valid input until user inputs a correct input or cancel the operation and once a correct input is passed it should continue from line 3, How can i do that?
I have tried a bit about it using try and except statement but their are many possible errors and i cannot find a way to run that line again without re-writing it in the except block and that too works for one error or the number of times i copy the same code in the except block.
You can put it in a while loop and check to see if an an input is an integer or not:
def is_integer(s):
try:
int(s)
return True
except ValueError:
return False
while True:
i = input("Enter an integer: " )
if is_integer(i):
print(i)
break
Try :
while True:
try:
i = int(input("Enter number : "))
break
except:
continue
Or you can use pass instead of continue.

NameError: name 'char' is not defined error

I'm trying to make a text game in python and i'm trying to debug the game right now.
I think this code I'm writing is supposed to type out the letters/characters one by one and make a typing effect.
here it is:
def setup_game():
### BACKSTORY TELLING
backstory = "something something boring backstory"
typeout(backstory)
def typeout(x):
time.sleep(0.03)
sys.stdout.write(char)
sys.stdout.flush()
option = input('> ')
if option.lower() == '> ok':
title_screen()
else:
print("please try again\n")
option = input('> ')
#Actual game
def start_game():
print_location()
main_game_loop()
setup_game()
but whatever i do it always gives me an error and i don't know how to fix it.
here it is:
Traceback (most recent call last):
File "textgame.py", line 612, in <module>
setup_game()
File "textgame.py", line 600, in setup_game
typeout(backstory)
File "textgame.py", line 604, in typeout
sys.stdout.write(char)
NameError: name 'char' is not defined
all the lines referenced in the error are in the code from the top.
I did find another post about the:
time.sleep(0.03)
sys.stdout.write(char)
sys.stdout.flush()
part and i tried doing what the answer said but instead it just gave me a different error which is what i have now.
help would be appreciated, thanks
You need to do something like:
sys.stdout.write(x)
Because char is not defined in your code. You're passing x to the function.

ERROR: Internal Python error in the inspect module

I was assigned in a edx python course to create a program that print out the longest substring that is in alphabetical order from a given string. I have written my code, but when i ran it I got "ERROR: Internal Python error in the inspect module.". I don't understand why. If someone could help me figure it out it would be great. This is the code:
s = 'azcbobobegghakl'
start=0
temp=0
while start<len(s):
initial=start
while True:
if ord(s[start])<=ord(s[start+1]):
start+=1
else:
start+=1
if len(s[initial:start])>temp:
sub=s[initial:start]
temp=len(sub)
break
print sub
and this is the full error:
Traceback (most recent call last):
File "C:\Users\Yoav\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.4.3105.win-x86_64\lib\site-packages\IPython\core\ultratb.py", line 776, in structured_traceback
records = _fixed_getinnerframes(etb, context, tb_offset)
File "C:\Users\Yoav\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.4.3105.win-x86_64\lib\site-packages\IPython\core\ultratb.py", line 230, in wrapped
return f(*args, **kwargs)
File "C:\Users\Yoav\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.5.4.3105.win-x86_64\lib\site-packages\IPython\core\ultratb.py", line 267, in _fixed_getinnerframes
if rname == '<ipython console>' or rname.endswith('<string>'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 3: ordinal not in range(128)
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.
Unfortunately, your original traceback can not be constructed.
Thanks!
Looks like the code mostly works, however when you call break, it only breaks out of the else block, and continues to run the while, with a value for start that is greater than the max index for s.
Try putting this code in a function, and using a return when you find the correct substring
Good luck!
def sub_finder(s):
start=0
temp=0
while start<len(s):
initial=start
while True:
if (start < len(s) - 1):
if ord(s[start])<=ord(s[start+1]):
start+=1
else:
start+=1
if len(s[initial:start])>temp:
sub=s[initial:start]
temp=len(sub)
break
else:
start+=1
if len(s[initial:start])>temp:
sub=s[initial:start]
temp=len(sub)
return sub
test = 'abcdaabcdefgaaaaaaaaaaaaaaaaaaaaaaaaaaaabbcdefg'
print sub_finder(test)
whoops, try this on for size.

raw_input() and sys.stdin misbehaves on CTRL-C

I am trying to detect a KeyboardInterrupt exception when CTRL-C is pressed during a raw_input() prompt. Normally the following code works just fine to detect the command:
try:
input = raw_input("Input something: ")
except KeyboardInterrupt:
do_something()
The problem comes when trying to intercept the input from sys.stdin. After adding some code in between raw_input() and sys.stdin, the CTRL-C command now results in two exceptions: EOFError followed by KeyboardInterrupt a line or two later. This is the code used to test:
import sys
import traceback
class StdinReplacement(object):
def __init__(self):
self.stdin = sys.stdin
sys.stdin = self
def readline(self):
input = self.stdin.readline()
# here something could be done with input before returning it
return input
if __name__ == '__main__':
rep = StdinReplacement()
while True:
info = None
try:
try:
input = raw_input("Input something: ")
print input
except:
info = sys.exc_info()
print info
except:
print '\n'
print "0:", traceback.print_traceback(*info)
print "1:", traceback.print_exception(*sys.exc_info())
Which results in the following being printed out:
0:Traceback (most recent call last):
File "stdin_issues.py", line 19, in <module>
input = raw_input("Input something: ")
EOFError: EOF when reading a line
None
1:Traceback (most recent call last):
File "stdin_issues.py", line 23, in <module>
print info
KeyboardInterrupt
Am I missing something obvious? Maybe intercepting the input in a bad way?
Found this fairly old page which seems like the same issue. No solution though:
https://mail.python.org/pipermail/python-list/2009-October/555375.html
Some environment details:
Python 2.7.3 (64-bit),
Windows 7 SP1 (64-bit)
------------------------------------------------------------------------
EDIT:
An update to the readline method of StdinReplacement fixed the issue.
def readline(self):
input = self.stdin.readline()
# here something could be done with input before returning it
if len(input) > 0:
return input
else:
return '\n'
It seems like the problem is that your readline method returns an empty line, thus signaling the end of file:
import sys
class Test(object):
def readline(self):
return ''
sys.stdin = Test()
raw_input('') # EOFError!
However modifying it such that it doesn't return an empty line makes the code work:
import sys
class Test(object):
def readline(self):
return '\n' # or 'a', or whatever
sys.stdin = Test()
raw_input('') # no error
The readline method should return an empty string only when the file finished. The EOFError is used to mean exactly this: raw_input expected the file to contain a line, but the file ended.
This is due to the call to PyFile_GetLine found at the end of the implementation of raw_input:
return PyFile_GetLine(fin, -1);
According to the documentation of PyFile_GetLine(PyObject *p, int n):
If n is less than 0, however, one line is read regardless of length,
but EOFError is raised if the end of the file is reached immediately.
Since it passes -1 as n the EOFError is raised when the EOF is found (i.e. you return an empty string from readline).
As far as I can tell the behaviour you see is only possible if you insert the input and also create an interrupt. Pressing only Ctrl+C doesn't generate any EOFError (at least on linux).

Categories

Resources