0

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.

enter image description here

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Michael E.
  • 61
  • 2
  • 7
  • 1
    Possible 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 Answers2

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, a ValueError 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 that ctrl-D is the equivalent of the Windows ctrl-Z). An EOFError 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