Check if input is positive integer

91,691

Solution 1

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)

Solution 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.

Share:
91,691
shivampaw
Author by

shivampaw

Updated on April 05, 2020

Comments

  • shivampaw
    shivampaw about 4 years

    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?

  • shivampaw
    shivampaw over 9 years
    Nope............. still same error.
  • Padraic Cunningham
    Padraic Cunningham over 9 years
    there is no error in my code and what error are you talking about?
  • shivampaw
    shivampaw over 9 years
    My full code: pastebin.com/yctSQLz0
  • Padraic Cunningham
    Padraic Cunningham over 9 years
    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
  • Lukas Graf
    Lukas Graf over 9 years
    @shivampaw that isn't even remotely related to the code that Padraic posted (or the traceback you posted, for that matter).
  • Marco Gamba
    Marco Gamba over 7 years
    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.
  • alper
    alper over 2 years
    Can we just do if number : to check if its positive