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

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

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 i.sstatic.net/mEy73.jpg
End of file won't result in ValueError.
it is not ValueError, but EOFError

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.