尝试 - 除了ValueError循环

时间:2016-11-06 09:50:48

标签: python try-catch

def enterNumber():
    number = input("Please enter a number to convert to binary. ")
    while True:
        try:
            int(number)
            convertDenary()
        except ValueError:
            enterNumber()
def convertDenary():
        binaryNumber = ['','','','','','','','']
        print(enterNumber())
        if enterNumber() > 128:
            enterNumber() - 128
            binaryNumber[0] == 1
enterNumber()

Try- Except ValueError按照我的意图循环,但它不会破坏。我尝试在int(数字)下添加break,移除while True:并添加到convertDenary()中以查看它是否会强制子程序停止并启动另一个但是它仍然无法正常工作。

我得到一个无限循环“请输入一个数字转换为二进制”。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

def convertToBinary(number):
   if number > 1:
       convertToBinary(number//2)
   elif number<1:
       enterNumber()

   print(number % 2,end = '')

def enterNumber():
    number = (input("Please enter a number to convert to binary : "))
    try:
        convertToBinary(int(number))
    except Exception as e:
        print(e)

enterNumber()