12

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?

5
  • How is it not working? Commented Oct 4, 2014 at 23:25
  • 1
    Check that the integer is greater than or equal to 0. Commented Oct 4, 2014 at 23:25
  • 1
    You mean if val >= 0 Commented Oct 4, 2014 at 23:25
  • after getting val, check it if it's greater than 0. if so, throw another exception. Commented Oct 4, 2014 at 23:26
  • Traceback (most recent call last): File "C:\Users\Office\Desktop\Python\If Else\Program\program.py", line 4, in <module> number = input("Enter a number: ") File "<string>", line 1, in <module> NameError: name 'hi' is not defined Commented Oct 4, 2014 at 23:30

2 Answers 2

25
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) 
Sign up to request clarification or add additional context in comments.

7 Comments

Nope............. still same error.
there is no error in my code and what error are you talking about?
My full code: pastebin.com/yctSQLz0
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
@shivampaw that isn't even remotely related to the code that Padraic posted (or the traceback you posted, for that matter).
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.