def main():
    decimal=int(input('pleas enter a binary sequence: '))
   
    number=binaryConvert(decimal)
    print("Contert to decimal: ", number)


def binaryConvert(decimal):
   
    if decimal == 0 :
        return '0'
    elif decimal==1:
        return '1'
    
    
    
    number=''
    while decimal == '1' and decimal == '0' :
        number=str(decimal%2)+ number
        number=number
        
        
    
main()

but i did work well with me
so could u fix or find where is my mistake

Dani AI

Generated

The task is to take a user-entered sequence of 1s and 0s (a binary string) and produce its decimal value. The original code mixed numeric and string types and tried a loop condition that can never be true; was correct about that logic error, and correctly hinted that Python has a built-in way to parse a binary string. A clean, robust approach is to treat the input as a string, validate its characters, optionally strip a 0b prefix or surrounding spaces, then accumulate the value left-to-right.

Here is a simple, self-contained conversion routine (no use of the built-in base parser shown earlier):

def binary_to_decimal(s):
    s = s.strip()
    if s.lower().startswith('0b'):
        s = s[2:]
    if not s or any(c not in '01' for c in s):
        raise ValueError('Input must be a non-empty sequence of 0 and 1')
    value = 0
    for ch in s:
        value = value * 2 + (1 if ch == '1' else 0)
    return value

This returns 0 for "0", 1 for "1", 5 for "101", 21 for "10101", etc. It avoids the common pitfalls: mixing types (strings vs ints), impossible boolean checks, and not validating input. If running very old Python (2.x), use raw_input() to get a string; in modern Python 3 input() already returns a string. For a one-line alternative, Python’s built-in parser can do the job as noted, but the manual method above makes validation and error messages explicit.

Recommended Answers

All 2 Replies

This statement will never be true

while decimal == '1' and decimal == '0' :
# ---- and this statement is meaningless
number=number

And str(decimal) will replace the binaryConvert() function. Also, press the code button to include your code in a readable (properly indented) form.

Hint ...

# binary for denary 9
bn = '1001'
dn = int(bn, 2)
print(dn)  # 9
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.