Notice: Undefined offset: 15199388 in /var/www/html/qa-external/qa-external-users.php on line 744
Tell me if i could shorten this code. (This code converts a binary number to decimal) - OnlineGDB Q&A
Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Tell me if i could shorten this code. (This code converts a binary number to decimal)

+6 votes
asked Mar 30, 2025 by Zinat Rehana (180 points)
binary = list(input('Enter a binary code: '))
binary.reverse()
power = 1
decimal = 0
for i in binary:
    if i == '1':
        decimal+=power
    power = power * 2
print(decimal)

2 Answers

+2 votes
answered Mar 31, 2025 by Peter Minarik (101,340 points)

By "shorten" I assume you mean to have less number of lines, right?

It's not less number of characters (e.g. by shortening variable names, such as power -> p).

It's not shortening execution time (i.e. making the code run faster).

You could do

print(int(input('Enter a binary code: '), 2))

See why, here.

0 votes
answered May 2, 2025 by Afia Raymond (350 points)

I dont think you should cause in software's like c,c++,c# and python you need to be very good with your wording because if you add or remove any thing it will most likely go into error mode .No cap there friendyes

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...