Python - Binary Addition,Loop无效

时间:2014-03-22 15:36:44

标签: python validation loops while-loop binary

我相对较新的编程,但熟悉python的基本概念。我的问题是: 我做了一个程序,它接受2个输入,检查它们长度小于8位,只包含1和0。一旦它接收并验证了它的2个二进制输入,它就将它们都转换为否定并将它们加在一起得到总数。一旦计算出总数,它就会将其转换回二进制并显示它。  我有所有的计算和输出工作,但第一点是让我麻烦。我想把输入的所有验证都放到一个循环中,所以当条件不满足时,它继续要求输入并且不允许接受任何不是8位二进制形式的输入。 我已经尝试了很多天了,最后决定在这里寻求专家的帮助:P希望有人可以帮助我,我将非常感谢我对循环的进一步了解。谢谢你,我现在的代码:)

valid = 0
while valid == 0 or correctcharacter == 0:
    firstnumber = input("First number is...")
    valid = 1
    correctcharacter = 0
    while correctcharacter == 0:
        correctcharacter = 1
        for number in firstnumber:
            if number != "0" and number != "1":
                valid = 0
                correctcharacter = 0

                if len(firstnumber) > 8:
                    valid = 0
#_________________________________________________________________________________________________________
valid = 0
while valid == 0:
    secondnumber = input("Second number is...")
    valid = 1
    correctcharacter = 0
    while correctcharacter == 0:
        correctcharacter = 1
        for number in secondnumber:
            if number != "0" and number != "1":
                valid = 0
                correctcharacter = 0

                if len(secondnumber) > 8:
                    valid = 0
#_________________________________________________________________________________________________________
multiple = 1
final1 = 0

for number in firstnumber[::-1]:
    final1 = final1 + int(number) * multiple
    multiple = multiple * 2

multiple = 1
final2 = 0

for number in secondnumber[::-1]:
    final2 = final2 + int(number) * multiple
    multiple = multiple * 2
#_________________________________________________________________________________________________________
total = final1 + final2

number = total
output = str()

while number > 0:
    output = str(number % 2) + output
    number = int(number / 2)

print("")
print("The total of {} and {} is {}.".format(firstnumber, secondnumber, output))

1 个答案:

答案 0 :(得分:1)

以防万一其他人需要帮助,这就是我解决问题的方法: http://docs.python.org/2/library/re.html

import re
valid = 0

while valid == 0:
    valid = 1
    firstnumber = input("Please enter firstnumber... ")
    if not re.match("^[0-1]{1,8}$", firstnumber):
        valid = 0
        print("Error! This program only accepts up to 8 0s and 1s!")