3.19.1: Lab R – Convert a 4 digit binary number
Question:
I have to write a program that converts a four-digit binary number and so far I’ve gotten credit for two outputs but one.
enter image description here
My problem is that in the third example, it’s not showing the zero, instead of 0101, it’s showing 101 for the binary number. I don’t know what to do, and I have to use % and //.enter image description here
And lastly, this is my code
Answers:
When I tried the snippet below
num = 0101
print(num)
It gave me this error
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
To get rid of this, try type casting of input;
bin_input = input()
print ("BINARY :",bin_input)
dec_num = int(bin_input)%4**2
print("DECIMAL :", dec_num)
but there is a math problem in your code (eg : 0111 should return 7 but this code returns 15)
Correct method :
bin_input = input()
print ("BINARY :",bin_input)
print("DECIMAL :", int(bin_input,2))
This code successfully solved the problem.
Hope this helps you 😮
I have to write a program that converts a four-digit binary number and so far I’ve gotten credit for two outputs but one.
enter image description here
My problem is that in the third example, it’s not showing the zero, instead of 0101, it’s showing 101 for the binary number. I don’t know what to do, and I have to use % and //.enter image description here
And lastly, this is my code
When I tried the snippet below
num = 0101
print(num)
It gave me this error
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
To get rid of this, try type casting of input;
bin_input = input()
print ("BINARY :",bin_input)
dec_num = int(bin_input)%4**2
print("DECIMAL :", dec_num)
but there is a math problem in your code (eg : 0111 should return 7 but this code returns 15)
Correct method :
bin_input = input()
print ("BINARY :",bin_input)
print("DECIMAL :", int(bin_input,2))
This code successfully solved the problem.
Hope this helps you 😮