Reputation: 35
import math
while True:
try:
user_bin = int(input('\nPlease enter binary number: '), 2)
except ValueError:
print('Please make sure your number contains digits 0-1 only.')
else:
print(user_bin)
I've just been browsing this site looking for tips on how to complete an assignment, the basics of the assignment is to have the user input an 8 bit binary number, and convert it to decimal. Or pop up an invalid input error in situations where it doesn't fit the requirements. The code above seemed interesting so I tested it and I genuinely don't understand which part of the code converts the binary to decimal. Any tips for the assignment as well as explanations would be appreciated.
Upvotes: 0
Views: 2031
Reputation: 15062
The part that converts the binary is int
. From the documentation:
if base is given, then x must be a string,
bytes
, orbytearray
instance representing an integer literal in radix base.
This means that int
accepts a string representing an integer, that you tell it the base of. E.g. here we give it "11"
, and tell it this is in base 2
, so it returns the integer 3
in decimal.
>>> int("11", 2)
3
Note that when supplying the base
argument, you have to give a string:
>>> int(11, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base
And you can't use digits that are invalid in the given base:
>>> int("21", 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '21'
Upvotes: 4