0

I am using Python 3.6 currently and my code currently is asking a user to input 2 integers and convert them into binary form, this is not a problem, the issue that I have is when it asks the user to input a number, if they put anything other than an integer, it will break the code and come up with an error, is there a specific few lines of code that will ensure that errors will not display if letters or floats are inputted?

def add():

    Num1 = int(input("Input the first number between 0 and 255, the calculated answer must not be above 255: "))
    Num2 = int(input("Input the second number between 0 and 255, the calculated answer must not be above 255: "))

I have tried one method which was:

if type(Num1) != int:
    print("Please input a number")
    add()

However I still get errors when testing the code.

I would like the code to detect that a string or float has been inputted, then reload the "def" function without giving a syntax error.

This is the print result:

Print result

smac89
  • 39,374
  • 15
  • 132
  • 179
PurpleWombat
  • 25
  • 1
  • 3
  • 6

1 Answers1

0

This is the gist of how to get an integer from the command line. It works using a while loop and try/except statements. You can add the checks for the integer range. You can use this code to create a function, which can be called twice for your particular problem.

n = None
while True:
    n = input('enter an integer')
    try:
        n = int(n)
        break
    except:
        continue
offwhitelotus
  • 1,049
  • 9
  • 15