0

I am writing a program that will ask the user to enter in an integer, and if it is not an integer, i will print "Error" and exit the program.

I tried this:

userNumber = input()
try:
    val = int(userNumber)
except ValueError:
    print("Error")
    exit()

But this is not working and is giving me an error.

How can I fix this?

8
  • what is the full text of the error? Commented Nov 9, 2014 at 20:17
  • You have a few NameError's in your code. valueError should be ValueError and printf should be print. Also, your indentation is messed up. Commented Nov 9, 2014 at 20:18
  • 1
    OP must getting Indentation error, Commented Nov 9, 2014 at 20:20
  • 1
    Please don't change your code after the errors have been pointed out... Commented Nov 9, 2014 at 20:20
  • if i try entering the letter X i get the error: line 7, in <module> userNumber = input() File "<string>", line 1, in <module> NameError: name 'x' is not defined Commented Nov 9, 2014 at 20:23

2 Answers 2

2

You're using Python 2 I think this is what you're looking for, and if you want a real print function (like Python 3 has), include this import at the top of your header:

from __future__ import print_function

userNumber = raw_input() # `input` in python 3, 
                         # the `input` function in '2' is actually processed as Python.
                         # equivalent to eval(raw_input(prompt))
try:
    val = int(userNumber)
except ValueError:
    print("Error") # This is a print statement without the import in Python 2, 
                   # In which case the parentheses are ignored.
    exit()

In Python 2, input is equivalent to eval(raw_input(prompt)).

Sign up to request clarification or add additional context in comments.

1 Comment

raw_input() not rawinput()
0

There are numerous problems with your program. The indentation is incorrect - the statements under try and except should be indented. Second, it's ValueError, not valueError. Third, you should be using print() instead of printf(). Finally, since you appear to be using Python 2, you should be using raw_input() instead of input().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.