2011-08-17 140 views
0

所以我有这个程序将二进制转换为十六进制。如果您输入非0或1或者字符串大于或小于8位,我也有一个返回值错误的部分。如何让程序自动重启后的值错误 - Python

但我现在想要的是,如果程序确实得到了值错误,我该如何编写它,以便在值错误后自动重新启动。

回答

2

括起来的代码在while循环。

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

这应该允许您的程序重复,直到它运行没有错误。

2

把你的代码放到一个循环:

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 
0

这里有一个小程序,把它放在上下文中:

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)) 

当你键入quit只停止。

相关问题