-1

How to inform error when user insert input which is not integer as requested?

For example:

number = int(input("Input the number: "))

I want to code something like: if number "is not" integer, so

if number is not integers 
            print("The input was not numerical value. Please try again")
        else:
            print ("Input "+ str(number) + " elements in the list:")

Can you help me.

Thank you!

  • 1
    Can you give an example of a non-integer that `int` could yield? – Scott Hunter Jan 13 '21 at 21:34
  • There have been already few posts about this, for example: https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except – Tomek Jan 13 '21 at 21:35
  • @ScottHunter you do not get my mean. For example: someone input character not integer for number so the system will print "The input was not numerical value. Please try again". – Nguyễn Thành Trung Jan 13 '21 at 21:39
  • You do not get *my* mean: `number` has already been assigned the result of calling `int` before you can do any testing. – Scott Hunter Jan 13 '21 at 21:51

1 Answers1

1

The try/except statement should fit nicely:

try:
    number = int(input("Input the number: "))
    print ("Input "+ str(number) + " elements in the list:")
except ValueError:
    print("The input was not numerical value. Please try again")
GuyPago
  • 173
  • 1
  • 2
  • 14