Python 如何确定一个数字是否为二进制?
Python 如何确定一个数字是否为二进制?,python,loops,if-statement,binary,Python,Loops,If Statement,Binary,my_l1:str=“0101011” 我执行以下代码: for character in my_l1: if character != '0' and character != '1': print (f"{my_l1} is not a binary number") else: print(f"{my_l1} is a binary number") 我得到这个输出: 0101011 is a binar
my_l1:str=“0101011”
我执行以下代码:
for character in my_l1:
if character != '0' and character != '1':
print (f"{my_l1} is not a binary number")
else:
print(f"{my_l1} is a binary number")
我得到这个输出:
0101011 is a binary number
0101011 is a binary number
0101011 is a binary number
0101011 is a binary number
0101011 is a binary number
0101011 is a binary number
0101011 is a binary number
我如何得到这样的单线输出
0101011 is a binary number.
您可以为..else添加
中断
和<代码>中断
将结束循环
my_l1:str = "0101011"
for character in my_l1:
if character != '0' and character != '1':
print (f"{my_l1} is not a binary number")
break
else:
print (f"{my_l1} is a binary number")
印刷品:
0101011 is a binary number.
您可以使用
all()
重写代码:
试试这个:
def isBinary(num: str):
for i in num:
if i not in ["0","1"]:
return False
return True
只是一个替代版本的想法。执行
int(my_l1,2)
并捕获一个可能的ValueError
。顺便说一句,输出与您的代码不匹配。如果最后一行缩进成为for
循环的一部分,您将得到此输出。对不起,是的,我没有注意到,我已经编辑了代码这一行适合我,尽管是快速问题,是否需要在if和else语句中都添加break?@incognitomodusbreak
只需要放入for循环内部的if
语句中。注意:else:
缩进在下,用于,而不是在下,如果不知情,那么使用all()
方法将是最短、最快的方法。欢迎使用StackOverflow!虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,只使用代码的答案是没有用的。谢谢你的提示@KimTang,我很感激。
def isBinary(num: str):
for i in num:
if i not in ["0","1"]:
return False
return True
if isBinary("000101") == True:
print("000101 is binary")
my_l1:str = "0101011"
isBinary=True ## We Assume it's True (i.e, the number is a binary) until we prove to
## the contrary, so this boolean variable is used to check (if binary
## or not)
for character in my_l1:
if character != '0' and character != '1':
sBinary=False ## once we find a number in the list my_l1 different
## than "0" and "1" it is not necessary to continue
## looping through the list, because the number is not
## a binary anymore, so we break in order to consume
## time
break
if isBinary: ## i.e, if isBinary==True then do :
print (f"{my_l1} is a binary number")
else:
print(f"{my_l1} is not a binary number")