11

I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.

number = input("Enter a number: ")
   ###################################

   try:
      val = int(number)
   except ValueError:
      print("That's not an int!")

The above code doesn't seem to be working.

Any ideas?

jww
  • 97,681
  • 90
  • 411
  • 885
shivampaw
  • 145
  • 1
  • 1
  • 9

2 Answers2

24
while True:
    number = input("Enter a number: ")
    try:
        val = int(number)
        if val < 0:  # if not a positive int print message and ask for input again
            print("Sorry, input must be a positive integer, try again")
            continue
        break
    except ValueError:
        print("That's not an int!")     
# else all is good, val is >=  0 and an integer
print(val)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Nope............. still same error. – shivampaw Oct 04 '14 at 23:36
  • 3
    there is no error in my code and what error are you talking about? – Padraic Cunningham Oct 04 '14 at 23:36
  • My full code: http://pastebin.com/yctSQLz0 – shivampaw Oct 04 '14 at 23:39
  • 6
    I have answered your question as posted, if you have another problem you should ask another question and fyi your code you posted in pastebin works fine – Padraic Cunningham Oct 04 '14 at 23:39
  • @shivampaw that isn't even remotely related to the code that Padraic posted (or the traceback you posted, for that matter). – Lukas Graf Oct 04 '14 at 23:43
  • Noting that this code only works with Python 3.x. Python 2.x users should use raw_input() instead of input(), since the latter does not even catch user errors, and parses user input before returning it. I believe the very root of @shivampaw 's problem was the mistaken use of the input() function instead of the correct raw_input(), which would have worked fine with his original traceback. – Marco Gamba Nov 03 '16 at 18:30
  • Can we just do `if number :` to check if its positive – alper Oct 14 '21 at 20:02
2

what you need is something like this:

goodinput = False
while not goodinput:
    try:
        number = int(input('Enter a number: '))
        if number > 0:
            goodinput = True
            print("that's a good number. Well done!")
        else:
            print("that's not a positive number. Try again: ")
    except ValueError:
        print("that's not an integer. Try again: ")

a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.

W1ll1amvl
  • 1,219
  • 2
  • 16
  • 30