0

I have to create a calculator for a small piece of schoolwork and I ask for inputs for the numbers and the symbol that will be used:

number1=int(input("\nWhat is your first number?"))

number2=int(input("\nWhat is your second number?"))

symbol=input("\nWhat is the symbol you will use?")

I want to know if there is any way I can make the int(input()) be asked again if they enter anything apart from an integer.

I'm not really good with Python atm so apologies if I missed something obvious. Also sorry if this thread is a duplicate.

Chad S.
  • 6,252
  • 15
  • 25

4 Answers4

1

The canonical method in python would be something like:

def get_integer_or_retry(mesg)
   while True:
      val = input(mesg) # or raw_input for python 2
      try:
          val = int(val)
          return val
      except ValueError: #trying to cast string as int failed
          pass # or you could let the user know their input was invalid

Note that if the user inputs 1.0 (or some other decimal that is also an integer), this will still throw ValueError (thanks Robᵩ ); if you need to handle floats that happen to be integers, you could do val = int(float(val)), but that will also accept (and silently round down) floating numbers ...

Foon
  • 6,148
  • 11
  • 40
  • 42
0

To know a variables type do type(var).

So, basically what you need to do:

 if type(variable)==int:
     do_something
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
0

Try isinstance method (https://docs.python.org/3/library/functions.html#isinstance)

>>> isinstance(5, int)
True
>>> isinstance("a", int)
False

in your case write a conditional, like,

if isinstance(number1, int):
    #do something

The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

marmeladze
  • 6,468
  • 3
  • 24
  • 45
0

I'm going to assume Python 2.7 for this answer.

I suggest first getting the input as a string, using raw_input, and then trying to convert that to an integer. Python will raise an exception if the conversion fails, which you can catch and prompt the user to try again.

Here's an example:

while True:
    try:
        s1 = raw_input('Enter integer: ')
        n1 = int(s1)
        # if we get here, conversion succeeded
        break
    except ValueError:
        print('"%s" is not an integer' % s1)

print('integer doubled is %d' % (2*n1))

and here's a sample execution, with inputs:

$ python 33107568.py
Enter integer: foo
"foo" is not an integer
Enter integer: 1.1
"1.1" is not an integer
Enter integer: 0x23123
"0x23123" is not an integer
Enter integer: 123
integer doubled is 246

On Python 3, you'd need to use input instead of raw_input; in Python 2, input evaluates the user input as a Python expression, which is rarely what is desired.

Rory Yorke
  • 2,166
  • 13
  • 13