![](/img/trans.png)
[英]How can I replace 1s in a binary array with natural numbers, maintaining the position of 0s?
[英]How can I use an exception to allow only a string binary input of 0s and 1s and reject everything else?
這是我的代碼,我不允許使用內置函數將 bin 轉換為十進制。 我必須執行 try 和 except ,但嘗試過但失敗了。
我需要輸入只接受 1 和 0。 我需要顯示一條錯誤消息並讓用戶在輸入任何其他內容時重試。
`#Declaration
strBinaryNumber= ""
intBinaryLength= 0
strBinaryInput= ""
intDecimalNumber= 0`
`#User input of binary number
strBinaryNumber= input("Enter your binary number: ")
intBinaryLength= len(strBinaryNumber)
strBinaryInput= strBinaryNumber`
`#Loop count for decimal conversion
intDecimalNumber = 0
while len(strBinaryNumber) > 0:
intDecimalNumber*=2
intDecimalNumber+= int(strBinaryNumber[0])
strBinaryNumber = strBinaryNumber[1:]`
`#Decimal Output
print("\nThe binary number is:", strBinaryInput)
print("\nThe length is:", intBinaryLength)
print("\nYour decimal number is:", intDecimalNumber)`
try-except 語句的基本思想是,如果代碼可能失敗,則有一些東西可以防止它被破壞。
嘗試:(您要運行的代碼)除了:(如果較早的代碼失敗則運行的代碼)
如果你把它放在一個函數中,然后讓它從except語句再次調用該函數,如果代碼失敗可能會有所幫助。
這是你的意思嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.