Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if input is positive integer [duplicate]

Tags:

python

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?

like image 597
shivampaw Avatar asked Oct 04 '14 23:10

shivampaw


2 Answers

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)
like image 171
Padraic Cunningham Avatar answered Sep 18 '22 18:09

Padraic Cunningham


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.

like image 39
W1ll1amvl Avatar answered Sep 18 '22 18:09

W1ll1amvl