亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何判斷一個數是否是二進制數?

如何判斷一個數是否是二進制數?

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 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號