简体   繁体   中英

I am making a code to turn a Binary number into decimal number, This is what I have done, Can someone tell where I am wrong, (i am 1 month into Python

n = int(input("Enter the binary number : "))

n_into_str = str(n)
lenf = len(n_into_str)


def calculate(n):
    ans = 0
    for i in range(lenf):
        z = n%10
        power = 2**i
        k = z*power
        value = z
        ans = ans + z
        
    print(ans)

calculate(n)

You are almost good, but you need ans = ans + k and ans = ans + z , and also divide n by 10, to remove the last digit

Version that uses math operation to select digit

def calculate(n: int):
    ans = 0
    for i in range(len(str(n))):
        z = n % 10
        n = n // 10
        power = 2 ** i
        k = z * power
        ans = ans + k
    print(ans)

n = int(input("Enter the binary number : "))
calculate(n)

Version that uses string indexing to select digit

def calculate(n: str):
    ans = 0
    for i, digit in enumerate(reversed(n)):
        power = 2 ** i
        k = int(digit) * power
        ans = ans + k
    print(ans)

n = input("Enter the binary number : ")
calculate(n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM