How do I avoid error while using int()? - python

I have a question concerning int(). Part of my Python codes looks like this
string = input('Enter your number:')
n = int(string)
print n
So if the input string of int() is not a number, Python will report ValueError and stop running the remaining codes.
I wonder if there is a way to make the program re-ask for a valid string? So that the program won't just stop there.
Thanks!

You can use try except
while True:
try:
string = input('Enter your number:')
n = int(string)
print n
break
except ValueError:
pass

Put the whole thing in an infinite loop. You should catch and ignore ValueErrors but break out of the loop when you get a valid integer.

What you're looking for isTry / Except
How it works:
try:
# Code to "try".
except:
# If there's an error, trap the exception and continue.
continue
For your scenario:
def GetInput():
try:
string = input('Enter your number:')
n = int(string)
print n
except:
# Try to get input again.
GetInput()

n = None
while not isinstance(n, int):
try:
n = int(input('Enter your number:'))
except:
print('NAN')

While the others have mentioned that you can use the following method,
try :
except :
This is another way to do the same thing.
while True :
string = input('Enter your number:')
if string.isdigit() :
n = int(string)
print n
break
else :
print("You have not entered a valid number. Re-enter the number")
You can learn more about
Built-in String Functions from here.

Related

PYTHON: Need help python, integer validation and can't use try except [duplicate]

How do I check if a user's string input is a number (e.g., -1, 0, 1, etc.)?
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
The above won't work since input always returns a string.
Simply try converting it to an int and then bailing out if it doesn't work.
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
See Handling Exceptions in the official tutorial.
Apparently this will not work for negative values, but it will for positive numbers.
Use isdigit()
if userinput.isdigit():
#do stuff
The method isnumeric() will do the job:
>>>a = '123'
>>>a.isnumeric()
True
But remember:
>>>a = '-1'
>>>a.isnumeric()
False
isnumeric() returns True if all characters in the string are numeric characters, and there is at least one character.
So negative numbers are not accepted.
For Python 3 the following will work.
userInput = 0
while True:
try:
userInput = int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
EDITED:
You could also use this below code to find out if its a number or also a negative
import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
print "given string is number"
you could also change your format to your specific requirement.
I am seeing this post a little too late.but hope this helps other persons who are looking for answers :) . let me know if anythings wrong in the given code.
If you specifically need an int or float, you could try "is not int" or "is not float":
user_input = ''
while user_input is not int:
try:
user_input = int(input('Enter a number: '))
break
except ValueError:
print('Please enter a valid number: ')
print('You entered {}'.format(user_input))
If you only need to work with ints, then the most elegant solution I've seen is the ".isdigit()" method:
a = ''
while a.isdigit() == False:
a = input('Enter a number: ')
print('You entered {}'.format(a))
Works fine for check if an input is
a positive Integer AND in a specific range
def checkIntValue():
'''Works fine for check if an **input** is
a positive Integer AND in a specific range'''
maxValue = 20
while True:
try:
intTarget = int(input('Your number ?'))
except ValueError:
continue
else:
if intTarget < 1 or intTarget > maxValue:
continue
else:
return (intTarget)
I would recommend this, #karthik27, for negative numbers
import re
num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')
Then do whatever you want with that regular expression, match(), findall() etc
natural: [0, 1, 2 ... ∞]
Python 2
it_is = unicode(user_input).isnumeric()
Python 3
it_is = str(user_input).isnumeric()
integer: [-∞, .., -2, -1, 0, 1, 2, ∞]
try:
int(user_input)
it_is = True
except ValueError:
it_is = False
float: [-∞, .., -2, -1.0...1, -1, -0.0...1, 0, 0.0...1, ..., 1, 1.0...1,
..., ∞]
try:
float(user_input)
it_is = True
except ValueError:
it_is = False
The most elegant solutions would be the already proposed,
a = 123
bool_a = a.isnumeric()
Unfortunately, it doesn't work neither for negative integers nor for general float values of a. If your point is to check if 'a' is a generic number beyond integers, I'd suggest the following one, which works for every kind of float and integer :). Here is the test:
def isanumber(a):
try:
float(repr(a))
bool_a = True
except:
bool_a = False
return bool_a
a = 1 # Integer
isanumber(a)
>>> True
a = -2.5982347892 # General float
isanumber(a)
>>> True
a = '1' # Actually a string
isanumber(a)
>>> False
This solution will accept only integers and nothing but integers.
def is_number(s):
while s.isdigit() == False:
s = raw_input("Enter only numbers: ")
return int(s)
# Your program starts here
user_input = is_number(raw_input("Enter a number: "))
This works with any number, including a fraction:
import fractions
def isnumber(s):
try:
float(s)
return True
except ValueError:
try:
Fraction(s)
return True
except ValueError:
return False
You can use the isdigit() method for strings.
In this case, as you said the input is always a string:
user_input = input("Enter something:")
if user_input.isdigit():
print("Is a number")
else:
print("Not a number")
Why not divide the input by a number? This way works with everything. Negatives, floats, and negative floats. Also Blank spaces and zero.
numList = [499, -486, 0.1255468, -0.21554, 'a', "this", "long string here", "455 street area", 0, ""]
for item in numList:
try:
print (item / 2) #You can divide by any number really, except zero
except:
print "Not A Number: " + item
Result:
249
-243
0.0627734
-0.10777
Not A Number: a
Not A Number: this
Not A Number: long string here
Not A Number: 455 street area
0
Not A Number:
I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):
This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)
a=(raw_input("Amount:"))
try:
int(a)
except ValueError:
try:
float(a)
except ValueError:
print "This is not a number"
a=0
if a==0:
a=0
else:
print a
#Do stuff
Here is a simple function that checks input for INT and RANGE. Here, returns 'True' if input is integer between 1-100, 'False' otherwise
def validate(userInput):
try:
val = int(userInput)
if val > 0 and val < 101:
valid = True
else:
valid = False
except Exception:
valid = False
return valid
If you wanted to evaluate floats, and you wanted to accept NaNs as input but not other strings like 'abc', you could do the following:
def isnumber(x):
import numpy
try:
return type(numpy.float(x)) == float
except ValueError:
return False
I've been using a different approach I thought I'd share. Start with creating a valid range:
valid = [str(i) for i in range(-10,11)] # ["-10","-9...."10"]
Now ask for a number and if not in list continue asking:
p = input("Enter a number: ")
while p not in valid:
p = input("Not valid. Try to enter a number again: ")
Lastly convert to int (which will work because list only contains integers as strings:
p = int(p)
while True:
b1=input('Type a number:')
try:
a1=int(b1)
except ValueError:
print ('"%(a1)s" is not a number. Try again.' %{'a1':b1})
else:
print ('You typed "{}".'.format(a1))
break
This makes a loop to check whether input is an integer or not, result would look like below:
>>> %Run 1.1.py
Type a number:d
"d" is not a number. Try again.
Type a number:
>>> %Run 1.1.py
Type a number:4
You typed 4.
>>>
I also ran into problems this morning with users being able to enter non-integer responses to my specific request for an integer.
This was the solution that ended up working well for me to force an answer I wanted:
player_number = 0
while player_number != 1 and player_number !=2:
player_number = raw_input("Are you Player 1 or 2? ")
try:
player_number = int(player_number)
except ValueError:
print "Please enter '1' or '2'..."
I would get exceptions before even reaching the try: statement when I used
player_number = int(raw_input("Are you Player 1 or 2? ")
and the user entered "J" or any other non-integer character. It worked out best to take it as raw input, check to see if that raw input could be converted to an integer, and then convert it afterward.
This will work:
print(user_input.isnumeric())
This checks if the string has only numbers in it and has at least a length of 1.
However, if you try isnumeric with a string with a negative number in it, isnumeric will return False.
Now this is a solution that works for both negative and positive numbers
try:
user_input = int(user_input)
except ValueError:
process_non_numeric_user_input() # user_input is not a numeric string!
else:
process_user_input()
Looks like there's so far only two answers that handle negatives and decimals (the try... except answer and the regex one?). Found a third answer somewhere a while back somewhere (tried searching for it, but no success) that uses explicit direct checking of each character rather than a full regex.
Looks like it is still quite a lot slower than the try/exceptions method, but if you don't want to mess with those, some use cases may be better compared to regex when doing heavy usage, particularly if some numbers are short/non-negative:
>>> from timeit import timeit
On Python 3.10 on Windows shows representative results for me:
Explicitly check each character:
>>> print(timeit('text="1234"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
0.5673831000458449
>>> print(timeit('text="-4089175.25"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
1.0832774000009522
>>> print(timeit('text="-97271851234.28975232364"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
1.9836419000057504
A lot slower than the try/except:
>>> def exception_try(string):
... try:
... return type(float(string)) == int
... except:
... return false
>>> print(timeit('text="1234"; exception_try(text)', "from __main__ import exception_try"))
0.22721579996868968
>>> print(timeit('text="-4089175.25"; exception_try(text)', "from __main__ import exception_try"))
0.2409859000472352
>>> print(timeit('text="-97271851234.28975232364"; exception_try(text)', "from __main__ import exception_try"))
0.45190039998851717
But a fair bit quicker than regex, unless you have an extremely long string?
>>> print(timeit('import re'))
0.08660140004940331
(In case you're using it already)... and then:
>>> print(timeit('text="1234"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.3882658999646083
>>> print(timeit('text="-4089175.25"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.4007637000177056
>>> print(timeit('text="-97271851234.28975232364"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.4191589000402018
None are close to the simplest isdecimal, but that of course won't catch the negatives...
>>> print(timeit('text="1234"; text.isdecimal()'))
0.04747540003154427
Always good to have options depending on needs?
I have found that some Python libraries use assertions to make sure that the value supplied by the programmer-user is a number.
Sometimes it's good to see an example 'from the wild'. Using assert/isinstance:
def check_port(port):
assert isinstance(port, int), 'PORT is not a number'
assert port >= 0, 'PORT < 0 ({0})'.format(port)
I think not doing a simple thing in one line is not Pythonic.
A version without try..except, using a regex match:
Code:
import re
if re.match('[-+]?\d+$', the_str):
# Is integer
Test:
>>> import re
>>> def test(s): return bool(re.match('[-+]?\d+$', s))
>>> test('0')
True
>>> test('1')
True
>>> test('-1')
True
>>> test('-0')
True
>>> test('+0')
True
>>> test('+1')
True
>>> test('-1-1')
False
>>> test('+1+1')
False
Try this! It worked for me even if I input negative numbers.
def length(s):
return len(s)
s = input("Enter the string: ")
try:
if (type(int(s))) == int:
print("You input an integer")
except ValueError:
print("it is a string with length " + str(length(s)))
Here is the simplest solution:
a= input("Choose the option\n")
if(int(a)):
print (a);
else:
print("Try Again")
Checking for Decimal type:
import decimal
isinstance(x, decimal.Decimal)
You can type:
user_input = input("Enter something: ")
if type(user_input) == int:
print(user_input, "Is a number")
else:
print("Not a number")
try:
val = int(user_input)
except ValueError:
print("That's not an int!")
This is based on inspiration from an answer. I defined a function as below. It looks like it’s working fine.
def isanumber(inp):
try:
val = int(inp)
return True
except ValueError:
try:
val = float(inp)
return True
except ValueError:
return False
a=10
isinstance(a,int) #True
b='abc'
isinstance(b,int) #False

How to understand exception condition usage in Python?

I came across a code that keeps asking the user for input until the user finally input an integer.
while True:
try:
n = input('Please enter an integer.')
n = int(n)
break
except ValueError:
print('Input is not an integer. Try again.')
print('Correct input of an integer.')
I tried out the code by entering a string as input and it asks me to try again. I assume it gives me a ValueError when it is executing
n = int(n)
as it can not convert a string to integer. Which the code then jumps to execute the except condition. However, I don't understand why am I still in the while loop after executing the except condition? It doesn't return True or something to continue running the while loop?
Also I entered a float as my input and it again ask me to try again. I do not understand as wouldn't int(n) be able to convert my float input to an integer without any ValueError?
You need to add a break statement after print('Input is not an integer. Try again.') or else it will keep looping back. As for handling floats, you could use int(float(n)) as suggested by tdelaney.
while True:
try:
n = input('Please enter an integer.')
n = int(float(n))
print('Correct input of an integer.')
break
except ValueError:
print('Input is not an integer. Try again.')
break
You can use the trace module to see statement by statement execution of the code:
$ python -m trace -t test.py
--- modulename: test, funcname: <module>
test.py(1): while True:
test.py(2): try:
test.py(3): n = input('Please enter an integer.')
Please enter an integer.notaninteger
test.py(4): n = int(n)
test.py(6): except ValueError:
test.py(7): print('Input is not an integer. Try again.')
Input is not an integer. Try again.
test.py(2): try:
test.py(3): n = input('Please enter an integer.')
Please enter an integer.1.1
test.py(4): n = int(n)
test.py(6): except ValueError:
test.py(7): print('Input is not an integer. Try again.')
Input is not an integer. Try again.
test.py(2): try:
test.py(3): n = input('Please enter an integer.')
Please enter an integer.3
test.py(4): n = int(n)
test.py(5): break
test.py(9): print('Correct input of an integer.')
Correct input of an integer.
In the first two test cases, the exception is run and you end up back at the top of the loop. In the final case, the break is hit which breaks you out of the nearest enclosing loop... the while.

Printing numbers as long as an empty input is not entered

If I'm asking for a user input of numbers which continues as long as an empty string is not entered, if an empty string is entered then the program ends.
My current code is:
n=0
while n != "":
n = int(input("Enter a number: "))
But obviously this isn't exactly what I want. I could remove the int input and leave it as a regular input, but this will allow all types of inputs and i just want numbers.
Do i ago about this a different way?
calling int() on an empty string will cause a ValueError so you can encapsulate everything in a try block:
>>> while True:
try:
n = int(input('NUMBER: '))
except ValueError:
print('Not an integer.')
break
NUMBER: 5
NUMBER: 12
NUMBER: 64
NUMBER:
not a number.
this also has the added benefit of catching anything ELSE that isn't an int.
I would suggest using a try/except here instead.
Also, with using a try/except, you can instead change your loop to using a while True. Then you can use break once an invalid input is found.
Also, your solution is not outputting anything either, so you might want to set up a print statement after you get the input.
Here is an example of how you can put all that together and test that an integer is entered only:
while True:
try:
n = int(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
If you want to go a step further, and handle numbers with decimals as well, you can try to cast to float instead:
while True:
try:
n = float(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break

Python how to only accept numbers as a input

mark= eval(raw_input("What is your mark?"))
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print "This is not a number"
So I need to make a python program that looks at your mark and gives you varying responses depending on what it is.
However I also need to add a way to stop random text which isn't numbers from being entered into the program.
I thought I had found a solution to this but it won't make it it past the first statement to the failsafe code that is meant to catch it if it was anything but numbers.
So pretty much what happens is if I enter hello instead of a number it fails at the first line and gives me back an error that says exceptions:NameError: name 'happy' is not defined.
How can I change it so that it can make it to the code that gives them the print statement that they need to enter a number?
remove eval and your code is correct:
mark = raw_input("What is your mark?")
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print("This is not a number")
Just checking for a float will work fine:
try:
float(mark)
except ValueError:
print("This is not a number")
Is it easier to declare a global value than to pass an argument,
In my case it's also gives an error.
def getInput():
global value
value = input()
while not value.isnumeric():
print("enter a number")
value = input("enter again")
return int(value)
getInput()
print(value)
#can't comment :)
You can simply cae to float or int and catch the exception (if any). Youre using eval which is considered poor and you add a lot of redundant statements.
try:
mark= float(raw_input("What is your mark?"))
except ValueError:
print "This is not a number"
"Why not use eval?" you ask, well... Try this input from the user: [1 for i in range (100000000)]
you can use the String object method called isnumeric. it's more efficient than try- except method. see the below code.
def getInput(prompt):
value = input(prompt)
while not value.isnumeric():
print("enter a number")
value = input("enter again")
return int(value)
import re
pattern = re.compile("^[0-9][0-9]\*\\.?[0-9]*")
status = re.search(pattern, raw_input("Enter the Mark : "))
if not status:
print "Invalid Input"
Might be a bit too late but to do this you can do this:
from os import system
from time import sleep
while True:
try:
numb = float(input("Enter number>>>"))
break
except ValueError:
system("cls")
print("Error! Numbers only!")
sleep(1)
system("cls")
but to make it within a number range you can do this:
from os import system
from time import sleep
while True:
try:
numb = float(input("Enter number within 1-5>>>"))
if numb > 5 or numb < 1:
raise ValueError
else:
break
except ValueError:
system("cls")
print("Error! Numbers only!")
sleep(1)
system("cls")
Actually if you going to use eval() you have to define more things.
acceptables=[1,2,3,4,5,6,7,8,9,0,"+","*","/","-"]
try:
mark= eval(int(raw_input("What is your mark?")))
except ValueError:
print ("It's not a number!")
if mark not in acceptables:
print ("You cant do anything but arithmetical operations!")
It's a basically control mechanism for eval().

How can I make a program determine whether or not the input is an int in python?

Good afternoon. I am trying to create a program to print descriptions of numbers. I'm in very basic python and am a bit stuck on this particular problem. Can anyone tell me how to have the program distinguish between numbers to continue the program, and the Q, Bye or carriage return to end the statement?
while True:
N = eval(input("Enter an input: number to continue, Q, bye or carriage return to quit")
if N == int
N => 0 print("positive")
else print("negative")
You can use isinstance:
if isinstance(N,int):
#do something
Note that this sort of thing isn't recommended. Especially when you're eval ing raw_input. Here I would try something like:
#python2
try:
N = int(raw_input("Enter integer:"))
except ValueError:
print "Not an integer!"
or on python3:
#python2
try:
N = int(input("Enter integer:"))
except ValueError:
print("Not an integer!")
I use a couple of different ways, depending on context:
try:
i = int(a)
except ValueError:
print >>sys.stderr, "Cannot be converted to integer"
or
if type(a) == type(1):
print "Yep, that's an int"

Categories