开发者

How do you make the program auto restart after value error - Python

So I have this program to convert a binary to hex. I also 开发者_如何学Pythonhave a part that returns a value error if you put in a non 0 or 1 or if the string is more or less than 8 digits.

But what I want now with it is if the program does get the value error how do I code it so that it automatically restarts after the value error.


Enclose the code in a while loop.

while True:
    try:
        #your code
    except ValueError:
        #reset variables if necesssary
        pass #if no other code is needed
    else:
        break

This should allow your program to repeat until it runs without errors.


Put your code into a loop:

while True:
    try:
        # your code here
        # break out of the loop if a ValueError was not raised
        break
    except ValueError:
        pass # or print some error


Here's a small program to put it in context:

while True:
    possible = input("Enter 8-bit binary number:").rstrip()
    if possible == 'quit':
        break
    try:
        hex = bin2hex(possible)
    except ValueError as e:
        print(e)
        print("%s is not a valid 8-bit binary number" % possible)
    else:
        print("\n%s == %x\n" % (possible, hex))

It only stops when you type in quit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜