为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

RISEBY 2023-12-12 09:55:25
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 number0101011 is a binary number0101011 is a binary number0101011 is a binary number0101011 is a binary number0101011 is a binary number0101011 is a binary number如何获得像这样的单行输出?0101011 is a binary number.
查看完整描述

3 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

您可以添加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")

       break

else:

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



查看完整回答
反对 回复 2023-12-12
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

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

 


查看完整回答
反对 回复 2023-12-12
?
繁花如伊

TA贡献2012条经验 获得超12个赞

尝试这个:


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


查看完整回答
反对 回复 2023-12-12
  • 3 回答
  • 0 关注
  • 56 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信