Very trivial program which could be thought as conclusion from the Quiz posts (thanks Gribouillis for inspiration for format)
Binary calculations
from __future__ import print_function
try:
input = raw_input
except:
pass
from operator import iadd, imul, idiv, imod, isub
oper = dict(zip('+*/%-', (iadd, imul, idiv, imod, isub)))
def get_bin(prompt='Bin value'):
while True:
try:
return int(input('%s: ' % prompt),2)
except ValueError:
print('Please enter string of 0 or 1 digits')
def get_op(prompt='Give operator'):
while True:
try:
op = input('%s (%s): ' % (prompt, ''.join(oper.keys()))).strip()
assert op in oper
return op
except AssertionError:
print('You must give one of the operators!')
if __name__ == '__main__':
first = get_bin('Give first binary number')
second = get_bin('Give second binary number')
op = get_op()
result = oper[op](first,second)
fl = max(len(bin(b)) for b in (first, second, result))
sl = fl - 2
sep = '-' * fl
print('''
{first:>{fl}b}
{op} {second:>{sl}b}
{sep}
{result:>{fl}b}
'''.format(**locals()))
Gribouillis 1,391 Programming Explorer Team Colleague
TrustyTony 888 pyMod Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.