python - How can I improve the functionality of this code -
a1 = input("enter 8 bit binary number convert: ") a1 = list(a1) ok = false; if a1[0] == '0': ok = true if a1[0] == '1': ok = true if a1[1] == '0': ok = true if a1[1] == '1': ok = true if a1[2] == '0': ok = true if a1[2] == '1': ok = true if a1[3] == '0': ok = true if a1[3] == '1': ok = true if a1[4] == '0': ok = true if a1[4] == '1': ok = true if a1[5] == '0': ok = true if a1[5] == '1': ok = true if a1[6] == '0': ok = true if a1[6] == '1': ok = true if a1[7] == '0': ok = true if a1[7] == '1': ok = true if ok == true: print("number binary!") n1 = 0 if a1[7] == '1': n1 = 1 if a1[6] == '1': n1 = n1 + 2 if a1[5] == '1': n1 = n1 + 4 if a1[4] == '1': n1 = n1 + 8 if a1[3] == '1': n1 = n1 + 16 if a1[2] == '1': n1 = n1 + 32 if a1[1] == '1': n1 = n1 + 64 if a1[0] == '1': n1 = n1 + 128 print("denary number is: " + str(n1))
use set:
a1 = input("enter 8 bit binary number convert: ") if set(a1) <= set('01'): print("number binary!")
this true if set(a1)
subset of set('01')
:
>>> set('10011') <= set('01') true >>> set('10011abc') <= set('01') false
you can use exceptions (and int()
binary -> integer conversion):
try: n1 = int(a1, 2) except valueerror: print("not binary") else: print("number binary") print("denary number is: {}".format(n1))
this has added advantage of converting binary input integer in 1 step.
if don't want or can use int()
, convert loop , use <<
left-shift each binary digit, , |
binary bitwise or add new digit:
n1 = 0 digit in a1: n1 = (n1 << 1) | (1 if digit == '1' else 0)
this rather round-about way number, @ least using binary logic now.
Comments
Post a Comment