我正在制作一个程序,可以将二进制转换成八进制、十进制和十六进制值。如何检查用户的输入值是否为二进制数? 代码如下:
def repeat1():
if choice == 'B' or choice == 'b':
x = input("Go on and enter a binary number: ")
y = int(x, 2)
print(x, "in octal is", oct(y))
print(x, "in decimal is", y)
print(x, "in hexidecimal is", hex(y))
print(" ")
def tryagain1():
print("Type '1' to convert from the same number base")
print("Type '2' to convert from a different number base")
print("Type '3' to stop")
r = input("Would you like to try again?")
if r == '1':
repeat1()
elif r == '2':
loop()
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
else:
print("You didn't enter any of the choices! Try again!")
tryagain1()
tryagain1()
提前谢谢你!在
我认为
try-except
是最好的方法。如果int(num, 2)
起作用,那么num
是二进制的。这是我的代码:输出示例:
^{pr2}$要检查一个数字是否为二进制,有两个步骤:检查它是否为整数,以及检查它是否只包含1和0
用户被要求输入一个数字,程序试图将其转换为整数。如果程序返回}。如果数字不是,变量
ValueError
,这意味着输入不是整数,程序将打印出该数字不是二进制的,while循环将再次开始。如果成功地将数字转换为整数,程序将遍历该数字(您必须将其转换为字符串,因为整数不可编辑),并检查x
中的所有数字是1
还是{binary
将变为False
。当程序成功地迭代了整个值,并且binary
是True
,它将从循环中中断。在相关问题 更多 >
编程相关推荐