What are the necessary requirements for coding decimal to binary [Python]?

Nathaniel

Okay, so I have had some help with some fellow users on this website and I found you can't just ask someone for code. I am not. I want to know some of the variables and stuff needed to code.

1) Need to have a raw_input so the user can type in their number. - I have seen you type:

raw_input("Please insert a number: ") #This allows you the user to type in a number. 

2) Need to have if, elif and else statements in my code to stop the user from typing in Anything but numerical values

-I think you need this:

if raw_input == '£' or '$' or '%' ETC 

but I think that might take too long :( Need help to make my if statements

3) Need to stop the user from entering a value below 1 and above 256.

I think you need this:

if raw_input > 256:
     return("Enter a value below 256")
elif raw_input < 1: return("Enter a value above 1")

4) Need to have the binary number presented as an '8 bit'

  • Example "00000111" same as "111".

Thanks, all information will be useful and I will try to reply to all of yous! Thanks!!!

Adam Smith

First of all, welcome to StackOverflow. It looks like you've been burned on questions in the past, and probably rightly so. This site is not typically well-suited for rank amateurs, who are better suited looking up a tutorial or reading documentation.

That said, you seem earnest in your efforts and have phrased the question in a meaningful way, so let me try to help:

1) Need to have a raw_input so the user can type in their number

That's correct, the way you store user input in Python2 is raw_input, as such:

variable_name = raw_input("Prompt")

2 and 3) Input validation

Basically both these points are the same -- how do I make sure my user entered data that's appropriate? There's lots of schools of thought on this, and you should read the difference between EAFP and LBYL coding, as well as concepts like duck-typing and etc. For now, let me just show you what I would do.

number = raw_input("prompt")
try:
    number = int(number)
except ValueError:
    # the user entered a value that can't be converted
    # to an integer, e.g. letters or a decimal number
    # so you'd handle that here, maybe with...
    print("Invalid number")
if 1 <= number <= 255:
    # user has entered a number below 1 or above 256
    # handle it as above, probably ending with:
    return

4) Conversion and return of value

Once you've done all the steps above, your number is GUARANTEED to either have thrown an error or be an integer between 1-256. From this point on, it's smooth sailing, just return the binary representation of that number (which is done with the built-in bin)

else:
    # number is now an integer between 1-256
    return bin(number) # bin(x) returns the number in base 2

Clarification

There are some terms here you've never seen before, so let me explain.

try:
    do_a_thing()
except Exception:
    handle_exception()

This is called a try/except block, and you use them when you're expecting the thing you're doing inside the block might throw an exception. For instance I might do:

try:
    f = open("path/to/a/file.txt", "r") # open a file in read mode
except (IOError,FileNotFoundError,PermissionError):
    print("Can't open that file because of an error")

I know when I try to open a file, it might fail if another application has it open, or if I'm not able to access the drive it's on, or even if the file doesn't exist! I then specify underneath how my code should handle each situation, and could even do

try:
    f = open("path/to/a/file.txt","r")
except IOError:
    handle_IOError()
except FileNotFoundError:
    make_file("path/to/a/file.txt")
except PermissionError:
    get_permission('path/to/a/file.txt')

To handle multiple errors in different ways.

Final Product

If this were my code, I would write it like this:

def get_binary(value):
    try:
        value = int(value)
        assert 1 >= value >= 255
    except ValueError:
        raise TypeError("Value must be an integer")
    except AssertionError:
        raise ValueError("Value must be between 1-255")
    return bin(value)

user_in = raw_input("Enter a number between 1-255: ")
print "The number in binary is {}".format(get_binary(user_in)[2:])

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Problems with a binary one-hot (one-of-K) coding in python

What requirements are necessary and sufficient for an ActiveX control to be used directly on an Excel worksheet?

Python program for converting decimal to binary

Decimal to Binary function, Python

Decimal to binary python algorithm

Decimal to binary with visualisation in python

Simple function to convert decimal number to binary in Python

What is the logic of this C++ Loop that converts Decimal to Binary

Python - Converting Binary (list) to Decimal

Converting Decimal Number To Binary In Python 3

Necessary requirements to use ranged algorithm on custom container

In python, what does [None] do/mean during coding of class?

Basic Binary to Decimal Conversion Program not working (Python)

Decimal number format and region coding

Binary To Decimal

binary to decimal using recursion,python

I dont know what these symbols in this code mean. Decimal to binary

What is recommended coding style for conditional operator in Python?

What is a module's binary in python

What was the file that has rot13 coding in Python and what was the name?

convert 32 bit, binary number to decimal in python

What are the requirements of a protocol factory in python asyncio?

Python 3.6 converting 8 bit binary to decimal

Converting decimal numbers to binary with functions in python

What's necessary to write in a CSV archive with Python using import CSV

Binary to Decimal conversion in Python

String Index Error for Binary to Decimal Python Solution

Convert 32 bit binary to a decimal in python

Numpy arrax of integers from decimal to binary in python