Check if input is a integer - python

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?

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

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().

Related

Python handling exceptions

In my program, I want to take in an input which should be a number.If the user inputs a string, however, the program returns an exception.I want the program set in such a way that the input is converted to int and then if the string is anything other than an int the program prints that "Stop writing please".Like for example:
x=input("Enter a number")
if int(x)=?: #This line should check whether the integer conversion is possible
print("YES")
else #This line should execute if the above conversion couldn't take place
print("Stop writing stuff")
You'll need to use try-except blocks:
x=input("Enter a number")
try:
x = int(x) # If the int conversion fails, the program jumps to the exception
print("YES") # In that case, this line will not be reached
except ValueError:
print("Stop writing stuff")
You can simply use a try-except block to catch the exceptional case, and inside there, print your statement. Something like this:
x=input("Enter a number")
try:
x=int(x)
print("YES")
except:
print("Stop writing stuff")

Why exception is not properly caught?

I have a piece of code.
import sys
while(True):
print "Enter a number: "
try:
number = int(sys.stdin.readline())
except ValueError:
print "Error! Enter again an integer value"
continue
finally:
print number
break
Here I expect when I enter a non-integer number, the output should be
Error! Enter again an integer value
and then it should ask for input. But it is printing the message but asking for further inputs. Please explain it or if am thinking it wrong.
If I handle with NameError, then error message is not even being printed and the program is exiting with a traceback call.
The finally clause always runs, whether an exception was caught or not. You want else, which runs when there was no exception.
Also: you don't need parentheses for a while, and you probably want the raw_input function which is a little nicer to use than messing with sys.stdin directly.
So I would do:
while True:
try:
number = int(raw_input("Enter a number: "))
except ValueError:
print "Error! Enter again an integer value"
continue
else:
print number
break
Your finally should be else, otherwise it will execute regardless of whether or not there was an exception.

except ValueError not tripping Python 3.4

Alright so I'm trying to basically prevent someone from typing a string value into the field:
#User selection
print("Which program would you like to run?")
print("(Type '9' if you wish to exit the menu)")
selection = int(input())
print()
#Security statement followed by case statement
while selection <= 0 or selection >= 10:
try:
print("That is an invalid selection, please input a proper selection.")
print("Which program would you like to run?")
selection = int(input())
print()
except ValueError:
print("Cmon man")
Plain and simple, it's not running. I've tried reorganizing everything and I haven't found a proper solution. Been looking around for almost an hour now. No help to the issue. Any kind souls?
Ignore the case statement portion btw, that's not even written yet.
P.S. Just keep getting usual "String isn't a number durr" response
("ValueError: invalid literal for int() with base 10: 'why'")
P.P.S. Issue is already pointed out. I'm apparently stupidly oblivious lol... Thanks for the help.
Your try...except doesn't cover the initial user input and so the ValueError isn't actually caught.
If you enter an int outside the bounds defined (0 >= x >= 10) as the first input then you can see the try...except blocks working.
You'll need to refactor your code so that the first input request is inside your try block and the loop or wrap the existing input request in another try...except.
Also, as a side note, input() can take a string argument that will be displayed as a prompt to the user.
selection = int(input("Which program would you like to run? "))

Getting safe user input in python

I'm writing a script that needs some very simple input from the user, and upon doing my research on this I am in a dilemma trying to work out the safest way to do it.
I only want an integer and stumbled across (what I thought was) a nice piece of code similar to (doing this from memory):
def getNumeric(prompt):
while True:
response = input(prompt)
try:
return int(response)
except ValueError:
print "please enter a number:",
This mostly worked, but if the user just pressed [enter] then it crashed. Turns out, I'm using python < 3, and the author wrote this for 3+. So now I have to rewrite for 2.7 to suit my needs. But how do I write it to cater for EITHER platform <3 and 3+?
I am writing something that could be used by others and want to make it the most portable I can. Should I bother?
As an aside, I am doing this for the Raspberry Pi, should I upgrade my python to 3, or leave it where it is (2.7.3)?
My suggestion is to upgrade the Pi to Python 3. There's no point developing Python code for two separate versions (unless it's a library, which you'd use much more precautions than just sharing functions). You can do:
# Python 3.x
def getNumeric(prompt):
while True:
try:
res = int(input(prompt))
break
except ValueError:
print("Numbers only please!")
return res
For Python 2.7.x, use raw_input() instead of input(). input() in Python 2 is not considered save since it evaluates the string given (and can be malicious).
Try:
def getNumeric(prompt):
while True:
response = input(prompt)
try:
if isinstance(response, int):
return int(response)
else:
print "please enter a number:"
except ValueError:
print "please enter a number:"

Input strings and integers

Just a quick question because I really can't find a simple solution to my problem.
Is there a way to get a user input that is meant to be a integer, but when a string is entered
the program will not break and instead displays "Error"
I've been trying to work around it by converting strings to integers and vice-versa, but I constantly get "invalid literal for int() with base 10" error, or when it displays "Error" it does so in an infinite loop.
Here's my code just to help clear the question
choice = input("Enter your choice: ")
while choice != 3:
if choice == 1:
get_songs()
print
main()
elif choice == 2:
read_songs()
print
main()
else:
print "Invalid choice"
So essentially I want the else operation to work for strings as well as for an integer that is greater than 3 or less than 1.
but I constantly get "invalid literal for int() with base 10" error
You get an exception, specifically a ValueError. You can catch the exception using an except block. For more info, refer to whatever language tutorial you've been using thus far, or try Google for except block Python.
when it displays "Error" it does so in an infinite loop.
When you detect that the input isn't correct, you need to get new input before you try the loop again. Put the input-getting stuff inside your loop. Do not use recursion (calling main() from within main) in addition to the loop; you're only going to confuse yourself this way. Because you don't get a value for choice until you're inside the loop, it's easier to explicitly break out of the loop when you find the appropriate choice value, instead of trying to control the loop with it (i.e. testing for it in the while condition).
We can also use continue to simplify the loop structure: instead of doing all the work in the try block, we limit that to the part where we extract a number. We use continue in the except block to skip the rest of the loop when we don't have an actual number, and only do the rest of the loop when we do. (After all, maybe the code we call for choice == 1 or choice == 2 could raise ValueError for some totally different reason, and we'd want to do something different about that.)
while True:
try:
choice = int(raw_input("Give me a number"))
except ValueError:
print "Could you at least give me an actual number?"
continue
if choice == 1:
do_something()
elif choice == 2:
do_something_else()
elif choice == 3:
break
else:
print "Try a different number"
Since that choice always != 3, you will get an infinite loop.
You should get input again if it jumps into the "else" condition.
In your code, the while loop should encapsulate the input() line. The following is a clearer alternative, however:
Create a function which gets user input:
def getInteger(prompt):
while True:
userIn = input(prompt)
try:
return int(userIn)
except ValueError:
print "Error"
Here's something: I dislike making the user enter "" around the strings.
ch = raw_input("Enter choice: ")
#ch *is* a string at this point
if ch.isdigit():
choice = int(ch)
else:
print "Invalid choice"
Edit (from comments):
isdigit may not handle locale encoding correctly. In Python 3, you can use isdecimal instead.
— J.F. Sebastian

Categories