-1

The following code is suppose to take a positive integer x and converts it to a binary string; for example tobin(101) should return the string '1100101' and tobin(2**5) should return the string '100000'.

def tobin(num):                     #Fucntion to get the number
    strvar = ""                     #Initialise strvar to an empty string
    while num != 0:                 #While num doesnt become 0 continue
        strvar = strvar+str(num % 2)    #Push the remainder of num/2 to strvar
        num = num//2                #Make num = num/2
    return strvar[::-1]             #Reverse the string using [::-1]


num = int(input("Enter the number : "))
print("Binary equivalent from funtion = ", tobin(num))
print("Binary equivalent from inbuilt funtion bin = ", bin(num))    #Here we use the inbuilt funtion

It seems to work but when i try inputting 2**5 in the input it gives me a error message.

ValueError: invalid literal for int() with base 10: '2**5'

It should be printing out 1000000.

can anyone tell me why im getting this error?

2 Answers2

1

You're getting the error because int parses only numbers. However if you still want to take the input in the expression format you've given, this should work. Another approach would be to take both numbers individually as inputs.

num = input("Enter the expression : ")
x,y= list(map(int, num.split("**")))
print("Binary equivalent from funtion = ", tobin(x**y))
print("Binary equivalent from inbuilt funtion bin = ", bin(x**y))  

Output

Enter the expression : 2**5
Binary equivalent from funtion =  100000
Binary equivalent from inbuilt funtion bin =  0b100000
vnk
  • 1,060
  • 1
  • 6
  • 18
0
num = int(eval(input("Enter the number : ")))

Do this. It will evaluate your entry and convert it to int. More about eval() here: Math operations from string

CyDevos
  • 395
  • 4
  • 11