如何判断一个数是否是二进制数?

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.


RISEBY
浏览 116回答 3
3回答

拉莫斯之舞

您可以添加break和for..else。break将结束循环。my_l1:str = "0101011"for character in my_l1:    if character != '0' and character != '1':       print (f"{my_l1} is not a binary number")       breakelse:    print (f"{my_l1} is a binary number")印刷:  0101011 is a binary number.您可以使用以下方法重写代码all():my_l1:str = "0101011"if all(ch=='0' or ch=='1' for ch in my_l1):    print (f"{my_l1} is a binary number")else:    print (f"{my_l1} is not a binary number")

慕标琳琳

 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") 

繁花如伊

尝试这个:def isBinary(num: str):    for i in num:        if i not in ["0","1"]:            return False    return Trueif isBinary("000101") == True:    print("000101 is binary")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python