我的目标是在列表中找到 1 或 0 以外的任何值并抛出错误并跳出循环。目前它可以检查任何非整数值就好了,但我希望避免某些数字(2-9)。我尝试检查 x != '1' 或 x != '0' ,但这没有用。我很感激任何帮助。decimalTotal = 0digit = 0index = 0power = 7flag = 'false'#get an 8-bit binary numberbinaryNumber = input("Please enter an 8-bit binary number: ")binary_list = list(binaryNumber)if len(binary_list) != 8: print() print("You did not enter an 8-bit length.") print()for x in binary_list: while (power >= 0): try: (int(binary_list[index])) except ValueError: flag = 'true' break else: decimalTotal += (int(binary_list[index])) * (2**(power)) index += 1 power -= 1if flag == 'false': print() print("The decimal value is: ", decimalTotal) print()else: print() print("Invalid binary value entered.") print()
1 回答
狐的传说
TA贡献1804条经验 获得超3个赞
如果您确实需要确保它恰好是 80或1s,那么可能一个简单的方法是:
import re
binaryNumber = input("Please enter an 8-bit binary number: ")
if not re.match('[01]{8}$', binaryNumber):
print('You did not enter exactly 8 zeros or ones.')
else:
print('Your number as decimal is:', int(binaryNumber, 2))
否则,如果您不关心它是否正好是 8 位,但可以更少或更多并且只想将其显示为小数,那么您可以这样做:
try:
print('Your number as decimal is:', int(binaryNumber, 2))
except ValueError: # couldn't be interpreted as binary
print('Your number was not a valid binary string')
添加回答
举报
0/150
提交
取消