My python code is supposed to take decimal numbers from 0 to 255 as arguments and convert them to binary, return invalid when the parameter is less than 0 or greater than 255
def binary_converter(x):
if (x < 0) or (x > 255):
return "invalid input"
try:
return int(bin(x)[2:]
except ValueError:
pass
The Test
import unittest
class BinaryConverterTestCases(unittest.TestCase):
def test_conversion_one(self):
result = binary_converter(0)
self.assertEqual(result, '0', msg='Invalid conversion')
def test_conversion_two(self):
result = binary_converter(62)
self.assertEqual(result, '111110', msg='Invalid conversion')
def test_no_negative_numbers(self):
result = binary_converter(-1)
self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed')
def test_no_numbers_above_255(self):
result = binary_converter(300)
self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed')
You already know how to check the range of the input argument, and how to return values. Now it's a simple matter of returning what the assignment requires.
In checking for valid input, all you've missed is to capitalize "Invalid".
For legal conversions, you just need to pass back the binary representation without the leading "0b", which you've almost done (remove that integer conversion, as two commenters have already noted).
So this is the final working code
def binary_converter(x):
if (x < 0) or (x > 255):
return "Invalid input"
try:
return (bin(x)[2:])
except ValueError:
pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.