I'm working on a school project and it specifically asks for a while not end-of-file loop which I don't know how to do in Python. I'm taking in user input (not from an external file) and computing some math in this infinite loop until they CTRL+C to break the loop. Any thoughts would really help me out. I've added part of the instruction if that helps clarify. Thanks.
Asked
Active
Viewed 2,632 times
0
-
1Possible duplicate of [How to find out whether a file is at its \`eof\`?](https://stackoverflow.com/questions/10140281/how-to-find-out-whether-a-file-is-at-its-eof) – felipsmartins May 19 '18 at 18:48
2 Answers
1
Your loop is supposed to stop on two conditions:
An illegal value was entered, ie some value that couldn't be converted to a
float
. In this case, aValueError
will be raised.You entered
ctrl-Z
, which means an EOF. (Sorry, having no Windows here, I just tested it on Linux, where I think thatctrl-D
is the equivalent of the Windowsctrl-Z
). AnEOFError
will be raised.
So, you should just create an infinite loop, and break out of it when one of these exceptions occur.
I separated the handling of the exceptions so that you can see what happens and print some meaningful error message:
while True:
try:
amount = float(input())
print(amount) # do your stuff here
except ValueError as err:
print('Terminating because', err)
break
except EOFError:
print('EOF!')
break
If you just want to quit without doing anything more, you can handle both exceptions the same way:
while True:
try:
amount = float(input())
print(amount) # do your stuff here
except (ValueError, EOFError):
break

Thierry Lathuille
- 23,663
- 10
- 44
- 50
0
Use the following:-
while True:
amount = raw_input("Dollar Amount: ")
try:
amount = float(amount)
# do your calculation with amount
# as per your needs here
except ValueError:
print 'Cannot parse'
break

nandal
- 2,544
- 1
- 18
- 23
-
Hi @Chrisz, kindly check his link for reference, he needs input from user and then process it accordingly. There was no need to open or read a file as per description on the link https://i.stack.imgur.com/mEy73.jpg – nandal May 19 '18 at 18:58
-
-